1

Consider the following two implementations of finding c(n,k), that is, finding the number of ways to choose n objects k at a time. How do the time-complexities for the two algorithms compare?

I had implemented the Dynamic Programming implementation, and tried on a few test cases like C(100,25), and it works pretty fast. I came up with the time complexity for this solution to be O(n^2).

The other implementation is using the prev_permutation or next_permutation available in C++ STL library, taken from here, originally from Rosetta Code. The documentation to this function here says it works in linear time upto half the distance between (first, last], so the loop it sits outside would make the entire complexity to be n squared again? (I'm not sure about this part, this is where I need help).

size_t combinations_dp (int n, int k) {
      vector <vector<size_t>> grid (n + 1, vector<size_t> (k + 1, 0));
      // base cases
      for (int i = 0; i <= n; i ++) {
            for (int j = 0; j <= k; j ++) {
                  if (i == j) grid[i][j] = 1;
                  if (j == 0) grid[i][j] = 1;
            }
      }
      for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= k; j++) {
                  if (j == 0 || j >= i) continue;
                  else {
                        grid[i][j] = grid[i-1][j-1] + grid[i-1][j];
                  }
            }
      }
      return grid[n][k];
}
void combinations_bits(N, K) {
  vector<bool> arr (K, 1);
  arr.resize(N, 0);
  long long count = 0;

  do {
    count ++;
  } while (prev_permutation(arr.begin(), arr.end()));

  cout << count << "\n";
}

I'm not sure how the complexities of the two implementations compare to each other, specially how the functions prev_permutation and next_permutation add to the time-complexity of the function.

nglglhtr
  • 163
  • 1
  • 7

0 Answers0