Problem Description
"Well, it seems the first problem is too easy. I will let you know how foolish you are later." feng5166 says.
"The second problem is, given an positive integer N, we define an equation like this:
N=a[1]+a[2]+a[3]+...+a[m];
a[i]>0,1<=m<=N;
My question is how many different equations you can find for a given N.
For example, assume N is 4, we can find:
4 = 4;
4 = 3 + 1;
4 = 2 + 2;
4 = 2 + 1 + 1;
4 = 1 + 1 + 1 + 1;
so the result is 5 when N is 4. Note that "4 = 3 + 1" and "4 = 1 + 3" is the same in this problem. Now, you do it!"
Input
The input contains several test cases. Each test case contains a positive integer N(1<=N<=120) which is mentioned above. The input is terminated by the end of file.
Output
For each test case, you have to output a line contains an integer P which indicate the different equations you have found.
Sample Input
4
10
20
Sample Output
5
42
627
解题思路 这道题和放苹果很像,比如说输入4,就是4个苹果,4个盘子,允许有空盘子,求有几种放法,所以最开始我是用递归做的,结果超时了,还是得用动态规划,用数组把每个结果存起来
首先先找出边界条件
if(dp[n][m]!=-1)//这是输入时做的标记,将每个数组初始值赋为-1,如果不等于-1,则说明数组已经标记过了,则不需要重复计算
return dp[n][m];
if(n<1||m<1) return dp[n][m]=0;
if(n==1||m==1) return dp[n][m]=1;
if(n<m)
return dp[n][m]=sum(n,n);
if(n==m)
return dp[n][m]=sum(n,m-1)+1;
递推式为: return dp[n][m]=sum(n,m-1)+sum(n-m,m);
代码如下
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
const int N=130;
int dp[N][N];
using namespace std;
int sum(int n,int m)
{
if(dp[n][m]!=-1)//避免大量的重复计算
return dp[n][m];
if(n<1||m<1) return dp[n][m]=0;
if(n==1||m==1) return dp[n][m]=1;
if(n<m)
return dp[n][m]=sum(n,n);
if(n==m)
return dp[n][m]=sum(n,m-1)+1;
return dp[n][m]=sum(n,m-1)+sum(n-m,m);//和放苹果那道题很像,可以去看我另一篇博客,有详细解释
}
int main()
{
int n;
while(~scanf("%d",&n))
{
memset(dp,-1,sizeof(dp));//将每个数组初始值赋为-1
printf("%d\n",sum(n,n));
}
return 0;
}