题目:
给定整数n,取若干个1到n的整数可求和等于整数m,编程求出所有组合的个数。比如当n=6,m=8时,有四种组合:[2,6], [3,5], [1,2,5], [1,3,4]。限定n和m小于120
(列代表n,行代表m)
代码如下:
#include<iostream> #include<vector> using namespace std; int main() { int N, M; cin >> N >> M; vector<vector <int>> dp(N + 1, vector<int>(M + 1, 0)); dp[1][0] = 1; dp[1][1] = 1; for (int i = 2; i <= N; i++) { for (int j = 1; j <= M; j++) { if (j < i) { dp[i][j] = dp[i - 1][j]; } else if (j == i) { dp[i][j] = dp[i - 1][j] + 1; } else { dp[i][j] = dp[i - 1][j] + dp[i - 1][j - i]; } } } cout << dp[N][M] << endl; return 0; }