經典面試題——從矩陣的左上角到右下角有多少種方法。
阿新 • • 發佈:2018-12-24
不多說,程式碼獻上,三種方法 #include <iostream> using namespace std; int mat[11][11]; int dp[11]; int main() { int n, m; int i, j; //樸素DP for(i = 1; i <= 10; ++i){ mat[1][i] = mat[i][1] = 1; } for(i = 2; i <= 10; ++i){ for(j = 2; j <= 10; ++j){ mat[i][j] = mat[i-1][j] + mat[i][j - 1]; } } //-------------------- while(scanf("%d %d", &n, &m) != EOF){ //滾動陣列 if(n < m){ n = n^m; m = n^m; n = n^m; } for(i = 1; i <= n; ++i){ dp[i] = 1; } for(i = 2; i <= m; ++i){ for(j = 2; j <= n; ++j){ dp[j] += dp[j - 1]; } } //------------------------------ printf("%d %d\n", mat[n][m], dp[n]);//結論應該為combo(n+m,min(n,m)) } return 0; }