Putting Apples
Problem Description
If we have n apples and k baskets, and we want to put all the apples into the baskets. We can leave some baskets empty. Now we want to know how many different ways we can put the apples. Be careful, the baskets are same, so {1,2} and {2, 1} are the same way.
Input
This problem contains multiple test cases.
For each test case, there are two integers n and k (1 <= n, k<= 100).
Output
For each test case, please output the number of ways we can put the apples.
Sample Input
7 3
2 1
Sample Output
8
1
后来看了张伟大学霸的报告然后查了查书之后知道了一下两点:
1、为了避免重复计算,要将已算出的会被重复使用的数据保存
2、篮子多苹果少时,模拟会将其作为不同情况进行计算。因此要将多出的篮子放弃,看作是苹果和篮子数量相同来计算
3、苹果多篮子少时,可以认为是一下两种情况的和
I. 每个篮子放一个,剩下的苹果按照篮子为空正常计算
II.一个篮子为空,剩下的篮子正常计算
即 d[n][k] = d[n-k][k] + d[n][k-1] 。此时n-k可正可负可为零,因此要分别对待,否则会造成re
n-k == 0 时,可以后退为 d[n][n] 的值,即 1 + d[n][k-1]
n-k < 0 时,可以后退为 d[n][k] 的 k > n 的情况,然后作为 d[n][n] 处理,因此可以被回避。
- #include<stdio.h>
- #include<string.h>
- int d[110][110];
- int find(int n,int k)
- {
- if ( d[n][k] != -1 ) return d[n][k];
- if ( n == 0 ) return 1;
- if ( k == 1 || n == 1 )
- {
- d[n][k] = 1;
- return 1;
- }
- if ( n < k ) k = n;
- d[n][k] = find(n-k,k) + find(n,k-1);
- return d[n][k];
- }
- int main()
- {
- int n,k;
- while ( scanf("%d%d",&n,&k) != -1 )
- {
- memset(d,-1,sizeof(d));
- if ( k > n ) k = n;
- if ( d[n][k] == -1 ) d[n][k] = find(n,k);
- printf("%d\n",d[n][k]);
- }
- return 0;
- }