Partition solution too slow

124 Views Asked by At

I am solving a problem that looks like partition problem to me: I have a sequence of integers and I should find one (if there are more than one solution I am supposed to output only single one) subset of these integers such that sum of them is exactly half of the sum of all integers.

I am trying to solve it via dynamic programming, but my solution is still too slow in test (I can pass only 2/10 tests and rest is too slow). Thanks for help.

My code:

void split(std::vector<int> seq, int sum, FILE * output){
  int n = seq.size() + 1;
  int m = sum + 1;
  bool** matrix = (bool**)malloc(m*sizeof(bool*));
  for(int i = 0;i<m;i++){
    matrix[i] = (bool*)malloc(n*sizeof(bool));
  }


  for(int i=1;i<=m-1;i++){
    matrix[0][i]=false;
  }
  for(int i=0;i<=n-1;i++){
    matrix[i][0]=true;
  }

  for(int i=1;i<=n-1;i++){
    for(int j=1;j<=m-1;j++){
      matrix[i][j] = matrix[i-1][j];
      if(matrix[i][j]==false && j>=seq[i-1])
    matrix[i][j] = matrix[i][j] || matrix[i-1][j-seq[i-1]];
    }
  }

  if(matrix[n-1][m-1]){
    int row = n-1;
    int column = m-1;

    while((row > 1) && (column > 0)){
      while(matrix[row-1][column]){row--;}
      fprintf(output, "%i ", row);
      column = column - seq[row-1];
    }
  }
  else{
    fprintf(output, "no");
  }
}
1

There are 1 best solutions below

2
karastojko On

If another approach is permitted, you can try by using Binary Search Tree. It should finish in O(n log n) time, where n is size of the sequence.