예제 #1
0
 std::vector<std::string> generateParenthesis(int n)
 {
     n_=n;
     int used_pairs=0;
     int left_pare=0;
     std::string parenthesis;
     backtrack(0, left_pare, used_pairs, parenthesis);
     return parenthesis_;
 }
예제 #2
0
//Top-level function
void toplevel(hls::stream<uint32> &input, hls::stream<uint32> &output) {
#pragma HLS INTERFACE ap_fifo port=input
#pragma HLS INTERFACE ap_fifo port=output
#pragma HLS RESOURCE variable=input core=AXI4Stream
#pragma HLS RESOURCE variable=output core=AXI4Stream
#pragma HLS INTERFACE ap_ctrl_none port=return

		uint32 command;

		init();

		side = input.read();
		ntiles = side * side;

		for(u8 t = 0; t < ntiles; t++)
			for (u8 e = 0; e < 4; e++)
				tiles[t][e] = input.read();

		mapcolours();

		// we start off with tile 0 in position 0
	    avail &= ~BIT36(0);

	    seq = 1;
	    while (!terminate) {
	    	if (seq == 1)
	    		solve();

			if (terminate) {
				output.write(0);
				break;
			}

			/* use magic flag to enforce sequencing */
			seq = 0;
			output.write(1);
			if (seq == 0)
				command = input.read();
			seq = 1;

			/* command 0: terminate */
			if (command == 0)
				break;

			/* command 1: write output */
			if (command == 1)
				for (u8 p = 0; p < ntiles; p++)
					for(u8 e = 0; e < 4; e++)
						output.write(colour(p, e));

			/* any other command (canonically 2) will cause search
			 * to continue without output */
			if (seq == 0)
				backtrack();
			seq = 1;
	    }
}
예제 #3
0
vector<string> WordBreakII::wordBreak(string s, unordered_set<string> &wordDict) {
    vector<string> result;
    vector<string> cur;
    vector<bool> canBreak(s.size() + 1, true);

    backtrack(s, wordDict, 0, cur, canBreak, result);

    return result;
}
예제 #4
0
    std::vector<std::string> generateParenthesis(int n)
    {
        if(n<=0) return solutions_;
        n_ = n;

        std::string solution;
        backtrack(solution, 0, 0);
        return solutions_;
    }
예제 #5
0
 bool makesquare(vector<int>& nums) {
     int sum = 0;
     for (int i=0; i<nums.size(); i++) sum += nums[i];
     if (sum % 4 != 0 || sum == 0) return false;
     vector<int> len(4,sum/4);
     sort(nums.begin(),nums.end());
     reverse(nums.begin(),nums.end());
     return backtrack(len,nums,0);
 }
int main(int argc, char const *argv[])
{
	int weight[N]={3,4,5,6,7};
	int value[N]={5,4,3,2,10};
	int answer[N];
	backtrack(weight,value,answer,0);
	printf("maxvalue=%d\n",maxvalue);
	printf("weighted=%d\n",weighted);
	return 0;
}
main(){
  int i,j,_a,_b;
  scanf("%d%d",&_a,&_b);
  for(i=1;i<=_a;i++)scanf("%d",a+i);
  for(i=1;i<=_b;i++)scanf("%d",b+i);
  for(i=1;i<=_a;i++)
    for(j=1;j<=_b;j++)
      lcs[i][j]=max(max(lcs[i-1][j],lcs[i][j-1]),lcs[i-1][j-1]+(a[i]==b[j]));
  backtrack(_a,_b);puts("");
}
예제 #8
0
 int uniquePaths(int m, int n) {
     int **mem = new int*[m];
     for(int i = 0; i<m; ++i) {
         mem[i] = new int[n];
         for(int j=0; j<n-1; ++j)
             mem[i][j] = (i==m-1)?1:-1;
         mem[i][n-1] = 1;
     }
     return backtrack(0, 0, m-1, n-1, mem);
 }
예제 #9
0
int main(void)
{
    scanf("%*d");
    while (scanf("%s", &input) == 1) {
        sort(input, strlen(input));
        backtrack(0);
    }

    return 0;
}
예제 #10
0
void backtrack(int col) {
    if (col == n) { /* do something.. */ return; }
    for (int row = 0; row < n; ++row) {
        if (!under_attack[row][col]) {
            placeQueen(row, col);
            backtrack(col + 1);
            removeQueen(row, col);
        }
    }    
}
예제 #11
0
 vector<vector<int>> permuteUnique(vector<int>& nums) {
     int *p = new int[nums.size()];
     for(int i = 0; i < nums.size(); i++)
         p[i] = 1;
     flag = p;
     sort(nums.begin(), nums.end());
     backtrack(nums, 0);
     delete []p;
     return vec;
 }
void backtrack(int *answer,int step){
	if(step==PEOPLE)
		display_outcome(answer);
	else
		for(int i=0;i<2;i++)
			if(condition(answer,step,i)){
				answer[step]=i;
				backtrack(answer,step+1);
			}
}
예제 #13
0
_ull backtrack( int row, int col, int conf, int id ){
    int i;
    
    if ( row == 0 && conf == 0 ) return 1;
    if ( row == 0 ) return 0;
    if ( col == C ) return backtrack( row - 1, 0, conf, id );
    if ( visited[row][col][conf][id] == now ) return config2[row][col][conf][id];
    
    visited[row][col][conf][id] = now;
    config2[row][col][conf][id] = 0;
    
    if ( grid[row][col] == '#' || ( (conf & ( 1 << col )) && id )){
        config2[row][col][conf][id] +=
            backtrack( row, col + 1, conf & (~(1<<col)), 1 );
        return config2[row][col][conf][id];
    }
    
    if ( col < (C-1) && grid[row][col+1]!='#' && !( conf & ( 1 << ( col + 1 )))){
        config2[row][col][conf][id] +=
            backtrack( row, col + 2, conf, 1 );
        if ( row > 1 && id && grid[row-1][col] != '#' )
            config2[row][col][conf][id] +=
                backtrack( row, col + 2, conf | (1<<col), 1);
        if ( row > 1 && grid[row-1][col+1] != '#')
            config2[row][col][conf][id] +=
                backtrack( row, col + 2, conf | (1<<(col+1)), 1);
    }
    
    if ( row > 1 && id && grid[row-1][col] != '#'){
        config2[row][col][conf][id] +=
            backtrack( row, col + 1, conf | ( 1 << col ), 1 );
        if ( col < ( C - 1 ) && grid[row-1][col+1] != '#'){ 
            if ( grid[row][col+1] == '#' || ( conf & ( 1 << ( col + 1 )) ))
                config2[row][col][conf][id] +=
                    backtrack( row, col + 2, conf | (3<<col), 1 );
            else
                config2[row][col][conf][id] += 
                    backtrack( row, col + 1, conf | (3<<col), 0 );
        }

        if ( col > 0 && grid[row-1][col-1] != '#' && !(conf & ( 1 << ( col - 1 )))){
            config2[row][col][conf][id] +=
                backtrack( row, col + 1, conf | (3<<(col-1)), 1 );
        }
    }
    
    return config2[row][col][conf][id];
}
예제 #14
0
 vector<string> findStrobogrammatic(int n) {
     // write your code here
     if(n <= 0) {
         return {""};
     }
     vector<string> ans;
     stack<char> s;
     backtrack(ans, s, n, n);
     return ans;
 }
예제 #15
0
 void backtrack(string& digits, vector<string>& ans,
                vector<string>& chars, string s, int idx, int n) {
     if(idx == n) {
         ans.push_back(s);
         return;
     }
     for(auto c: chars[digits[idx]-'0']) {
         backtrack(digits, ans, chars, s + c, idx + 1, n);
     }
 }
예제 #16
0
// backtrack - completes the filling of the board using recursive backtracking
int backtrack(int row, int col) {
	
	// If the board is full, then we have a solution!!!
	if (is_full_board())
		return 1;


	if (board[row][col] != ' ') {
		if (col == BOARD_SIZE - 1) {
			if (backtrack(row + 1, 0))
				return 1;
		} else {
			if (backtrack(row, col + 1))
				return 1;
		}
	}

	int i;

	// Iterate through all possible sudoku numbers
	for (i = 0; i < BOARD_SIZE; i++) {
		if (is_legal(row, col, i + 1 + '0')) {
				
			// Temporarily assign i to the board
			board[row][col] = i + 1 + '0';

			// Check recursively if i results in a solved board 
			if (col == BOARD_SIZE - 1) {
				if (backtrack(row + 1, 0))
					return 1;
			} else {
				if (backtrack(row, col + 1))
					return 1;
			}
		}
	}
		
	// At the is point none of the numbers will result in a solved
	// board, thus we must initiate backtracking
	board[row][col] = ' ';
	return 0;
}
예제 #17
0
int main(void)
{
    scanf("%*d");
    while (scanf("%s", &input) == 1) {
        qsort(input, strlen(input), sizeof(char), cmp);
        backtrack(0);
        putchar('\n');
    }

    return 0;
}
예제 #18
0
파일: sudoku.cpp 프로젝트: Atonej/CIS263
		/***********************************
 		* This method will print the board at the 
 		* start of the game and the end
 		*
 		***********************************/
		void printBoard(){
			std::cout << "Sudoku Board: Before" << std::endl;
			std::cout <<  "______________" << std::endl;
			for(int i=0;i<9; i++){
				for(int j = 0; j<9 ; j++){
					if (j==8){
						std::cout <<  board[i][j] << "|" << std::endl;
						if(i == 2 || i == 5 || i == 8)
							//help to make look like an actual board
							std::cout <<  "______________" << std::endl;

					}
					else{
					//catch zeros make them appear blank
					std::cout << board[i][j] ;//<< " " ;
					if(j == 2 || j == 5 || j == 8)
							//separator
							std::cout <<  "||";				
					}
				}
	
			}

			//go through board	
			if(backtrack(board)== true){
				//complete = backtrack(board);
			std::cout << "Sudoku Board: Solved" << std::endl;
			std::cout <<  "______________" << std::endl;
			for(int i=0;i<9; i++){
				for(int j = 0; j<9 ; j++){
						
					//at the end of the line
					if (j==8){
					
						std::cout <<  board[i][j] << "|" << std::endl;
						if(i == 2 || i == 5 || i == 8)
							//help to make look like an actual board
							std::cout <<  "______________" << std::endl;

						}
					else{
					//catch zeros make them appear blank
					std::cout << board[i][j] ;//<< " " ;
					if(j == 2 || j == 5 || j == 8)
							//separator
							std::cout <<  "||";
					
					}
				}
	
			}
		
		}
		}
예제 #19
0
int eightQueens(void)
{
    int i;
    num = 0;
    for(i = 1; i <= N; i++)
        column[i] = 1;
    for(i = 1; i <= 2*N; i++)
        rup[i] = lup[i] = 1;
    backtrack(1);
    return 0;
}
예제 #20
0
파일: 8-queens.c 프로젝트: LihuaWu/recipe
main()
{
	int a[NMAX];			/* solution vector */
	int i;				/* counter */

	for (i=1; i<=10; i++) {
		solution_count = 0;
		backtrack(a,0,i);
		printf("n=%d  solution_count=%d\n",i,solution_count);
	}
}
예제 #21
0
void Alignment<R,L,AL>::getOptGlobalAlignment(PPForestAli<L,AL> &ppfali)
{
  Uint node=0;

  // allocate a forest of the maximal size that a forest alignment can have
  ppfali.initialize(m_ppfx->size()+m_ppfy->size());
  backtrack(ppfali,0,m_ppfx->getMaxLength(0),0,m_ppfy->getMaxLength(0),node);
  ppfali.setSize(node);
  ppfali.calcSumUpCSF();
  ppfali.calcRMB();
}
예제 #22
0
파일: genetic.c 프로젝트: cen5bin/acm
int backtrack()
{
  if (end == target)
    return 1;
  ++end;
  for (end[-1]='N' ; end[-1]<='P' ; end[-1]++)
    if (isThue() && backtrack())
      return 1;
  --end;
  return 0;
}
예제 #23
0
파일: 052.cpp 프로젝트: nolink/algorithm
 void backtrack(vector<int>& board, int i, int n, int& count){
     if(i == n){
         count++;
         return;
     }
     board.push_back(-1);
     for(int j=0;j<n;j++){
         board[i] = j;
         if(valid(board, i, n)) backtrack(board, i + 1, n, count);
     }
 }
예제 #24
0
파일: fold.c 프로젝트: jrgreen7/SMIRP
float fold(const char *string, char *structure) {
  int i, length, energy, bonus=0, bonus_cnt=0;

  circ = 0;
  length = (int) strlen(string);
  if (length>init_length) initialize_fold(length);
  if (fabs(P->temperature - temperature)>1e-6) update_fold_params();

  encode_seq(string);

  BP = (int *)space(sizeof(int)*(length+2));
  make_ptypes(S, structure);

  energy = fill_arrays(string);

  backtrack(string, 0);

#ifdef PAREN
  parenthesis_structure(structure, length);
#else
  letter_structure(structure, length);
#endif

  /* check constraints */
  for(i=1;i<=length;i++) {
    if((BP[i]<0)&&(BP[i]>-4)) {
      bonus_cnt++;
      if((BP[i]==-3)&&(structure[i-1]==')')) bonus++;
      if((BP[i]==-2)&&(structure[i-1]=='(')) bonus++;
      if((BP[i]==-1)&&(structure[i-1]!='.')) bonus++;
    }

    if(BP[i]>i) {
      int l;
      bonus_cnt++;
      for(l=1; l<=base_pair[0].i; l++)
	if((i==base_pair[l].i)&&(BP[i]==base_pair[l].j)) bonus++;
    }
  }

  if (bonus_cnt>bonus) fprintf(stderr,"\ncould not enforce all constraints\n");
  bonus*=BONUS;

  free(S); free(S1); free(BP);

  energy += bonus;      /*remove bonus energies from result */

  if (backtrack_type=='C')
    return (float) c[indx[length]+1]/100.;
  else if (backtrack_type=='M')
    return (float) fML[indx[length]+1]/100.;
  else
    return (float) energy/100.;
}
예제 #25
0
파일: 0030.c 프로젝트: lanevok/AOJ
void backtrack(int i,int k){
  //  flg++;
  //  if(flg>20)
  //   exit(1);
  //  printf("Call:[%d,%d]\n",i,k);
  if(i==10){
    if(k==n){
      if(s==sum(k))
	cnt++;
    }
    //    puts("return");
    return;
  }
  else{
    backtrack(i+1,k);
    t[k]=i;
    backtrack(i+1,k+1);
  }
  //  puts("fall");
}
예제 #26
0
파일: 046.cpp 프로젝트: nolink/algorithm
 void backtrack(vector<vector<int>>& ret, vector<int>& nums, int idx){
     if(idx >= nums.size()){
         ret.push_back(nums);
         return;
     }
     for(int i = idx;i < nums.size();i++){
         swap(nums[idx], nums[i]);
         backtrack(ret, nums, idx+1);
         swap(nums[i], nums[idx]);
     }
 }
예제 #27
0
void event_grapht::graph_explorert::collect_cycles(
  std::set<critical_cyclet>& set_of_cycles, 
  memory_modelt model)
{
  /* all the events initially unmarked */
  for(unsigned i = 0; i<egraph.size(); i++)
    mark[i] = false;

  std::list<unsigned>* order=0;
  /* on Power, rfe pairs are also potentially unsafe */
  switch(model)
  {
  case TSO:
  case PSO:
  case RMO:
    order=&egraph.po_order;
    break;
  case Power:
    order=&egraph.poUrfe_order;
    break;

  case Unknown:
    assert(false);
  }

  if(order->empty())
    return;

  /* if we only consider a limited part of the graph */
  order=order_filtering(order);

  if(order->empty())
    return;

  for(std::list<unsigned>::const_iterator st_it=order->begin(); 
    st_it!=order->end(); ++st_it)
  {
    unsigned source=*st_it;
    egraph.message.debug() << "explore " << egraph[source].id << messaget::eom;
    backtrack(set_of_cycles, source, source, 
      false, max_po_trans, false, false, false, "", model);

    while(!marked_stack.empty())
    {
      unsigned up=marked_stack.top();
      mark[up]=false;
      marked_stack.pop();
    }
  }

  /* end of collection -- remove spurious by thin-air cycles */
  if(egraph.filter_thin_air)
    filter_thin_air(set_of_cycles);
}
예제 #28
0
 void backtrack(vector<int> n, int k) {
     if (k == n.size())
         vec.push_back(n);
     else {
         for (int i = k; i < n.size(); i++)
             if(n[k] != n[i] || k == i) {
                 swap(n[k], n[i]);
                 backtrack(n, k + 1);
             }
     }
 }
예제 #29
0
파일: #216.cpp 프로젝트: fr-ant/LeetCode
	void backtrack(int start, int k, int target){
    	if (target==0 && k==0){
        	res.push_back(tmp);
        	return;
    	}
    	for (int i=start; i<=min(10-k, target); i++){
        	tmp.push_back(i);
        	backtrack(i+1,k-1,target-i);
        	tmp.pop_back();
    	}
	}
예제 #30
0
void backtrack(std::string & s, size_t i, int used) {
	if (i == s.size()) {
		handle(s);
	}

	for (int d = 1; d <= 9; ++d)
		if (!(used & (1<<d))) {
			s[i] = static_cast<char>(d+'0');
			backtrack(s, i+1, used|(1<<d));
		}
}