Binomial Coefficient Pseudocode using Divide-and-Conquer
int(int n, int k) // Inputs: nonnegative integers n and k, where k <= n. // Outputs: the binomial coefficient nCk { if (k == 0 || n == k) return1; else return bincoeff(n-1, k-1) + bincoeff(n-1, k); }
이항계수를 분할정복법으로 구현하기는 간단하지만 효율적이지는 않다. bincoeff(n-1, k-1)과 bincoeff(n-1, k)는 모두 bincoeff(n-2, k-1)의 결과가 필요하고 이 값은 해당 알고리즘에서 중복 계산되므로 알고리즘의 효율이 떨어진다. 분할정복법은 나눠진 문제들 간에 서로 연관성이 없는 문제를 해결하는데 적합함을 상기하자.
Binomial Coefficient Using Dynamic Programming
Algorithm Design
Establish a recursive property. B[i][j] will contain $ _iC_j$
intbincoeff2(int n, int k) { index i, j; int B[0..n][0..k];
for (i = 0; i <= n; ++i) for (j = 0; j <= minimum(i,k); ++j) if (j == 0 || j == i) B[i][j] = 1; else B[i][j] = B[i-1][j-1] + B[i-1][j];
return B[n][k]; }
Source Code
// File: binomial2.h
#define BINCOEFF_H
namespace algorithms { intbinomial_coefficient(int** b, int n, int k); // Input: nonnegative integers n and k, where k <= n. // Output: the binomial coefficient (n, k).
} // namespace algorithms
#endif
// File: binomial2.cpp #include<algorithm> // Provides min #include"binomial2.h"
namespace algorithms { intbinomial_coefficient(int** B, int n, int k) { // Improvement to the algorithm would be // to take advantage of the fact that (n,k) = (n, n-k) // if ((n/2) < k) // k = n - k;
for (int i = 0; i <= n; ++i) { for (int j = 0; j <= std::min(i, k); ++j) { if (j == 0 || j == i) B[i][j] = 1; else B[i][j] = B[i - 1][j - 1] + B[i - 1][j]; } }
int** get_matrix_space(int m, int n) { // Allocate the matrix // Please make sure that we need to allocate [m+1][n+1] int **data = newint *[m + 1]; for (int i = 0; i < m + 1; ++i) data[i] = newint[n + 1];
// Initialize the matrix for (int i = 0; i < m + 1; ++i) for (int j = 0; j < n + 1; ++j) data[i][j] = 0; return data; }
voidrelease_matrix_space(int** b, int m) { for (int i = 0; i < m + 1; ++i) delete[] b[i]; delete[] b; }
Time Complexity Analysis
Basic operation
the number of passes through the for-j loop
Input size
n, k
Every-Case Time Complexity
$T(n) = frac{k(k+1)}{2} + (n-k+1)(k+1) = frac{(2n-k+2)(k+1)}{2} in Theta (nk)$
近期评论