- 描述
-
把一个正整数m分成n个正整数的和,有多少种分法?
例:把5分成3个正正数的和,有两种分法:
1 1 3
1 2 2
- 输入
- 第一行是一个整数T表示共有T组测试数据(T<=50)
每组测试数据都是两个正整数m,n,其中(1<=n<=m<=100),分别表示要拆分的正数和拆分的正整数的个数。 - 输出
- 输出拆分的方法的数目。
- 样例输入
-
2 5 2 5 3
- 样例输出
-
2 2
- 来源
- [张云聪]原创
- 上传者
- 张云聪
- 思路:这种类型的和前面的整数划分原理相同,和分苹果题类似,且按那个题目更容易讲解:
- 指定了分的份数,那我先每个盘子放一个不就行了,后面放的时候就可以随便放,不需要保证非空了,但是主要要保证份额,不能超过份数,所以
- 可以写为:
- dp[i][j] = dp[i][j-1] + dp[i - 1][j]; 表示现在总数是i,有j个盘子,考虑第j个盘子要不要放,放那就放一个,不放盘子减一(相当于安排好了刚刚的那个盘子)
- dp[i][j]: i表示总数,j表示第几个盘子
-
#include <bits/stdc++.h> using namespace std; int dp[15][15]; //dp[i][j]: i表示总数,j表示第几个盘子 int find(int n, int m){ if(n < 0 || m < 0) return 0; if(m == 0 && n > 0) return 0; if(m == 0 && n >= 0){ return dp[n][m] = 1; } if(dp[n][m]){ //如果已经填充过,不需要再次进行 return dp[n][m]; } return dp[n][m] = find(n - m, m) + find(n, m - 1); } int main(){ int t; cin >> t; while(t--){ int n, m; memset(dp, 0, sizeof(dp)); cin >> n >> m; cout << find(n - m, m) << endl; } return 0; }