杭電1028——整數拆分(遞迴實現)
問題描述
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
問題分析
整數劃分問題是將一個正整數n拆成一組數連加並等於n的形式,且這組數中的最大加數不大於n。
如6的整數劃分為
6
5 + 1
4 + 2, 4 + 1 + 1
3 + 3, 3 + 2 + 1, 3 + 1 + 1 + 1
2 + 2 + 2, 2 + 2 + 1 + 1, 2 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1
共11種。
主要是通過遞迴來實現,遞迴函式為int split(int n,int m) ,其中n是待劃分的正整數,m是劃分中最大的加數。返回值即為劃分的種數。
(1)當n=1或者m=1,split(n,m)=1;
(2)當m>n,最大加數不可能比要劃分的正整數大,所以,split(n,m)=split(n,n)
(3)當n=m,split(n,m)=split(n,m-1)+1。比如說:split(6,6)=1+split(6,5)。也就是說整數6的劃分可以分為6和最大加數為5的兩部分。
(4)當n>m,split(n,m)=split(n,m-1)+split(n-m,m)。比如說split(6,4)=split(6,3)+split(2,4)
其中:
split(6,3) :
3 + 3, 3 + 2 + 1, 3 + 1 + 1 + 1
2 + 2 + 2, 2 + 2 + 1 + 1, 2 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1
split(2,4):
4 + 2, 4 + 1 + 1
這些劃分方法有相同的整數m(這裡是4)。所以,把所有劃分都減去4,就相當於求正整數n-m的劃分種類數。
AC程式碼
# include<stdio.h>
# include<string.h>
#define MAX 125
int num[MAX][MAX];//使用陣列將已經計算過的值儲存起來,免得遞迴重複計算
int split(int n,int m);
int main()
{
memset(num,0,sizeof(num));
int N;
while(scanf("%d",&N)!=EOF)
{
printf("%d\n",split(N,N));
}
return 0;
}
int split(int n,int m)
{
if(num[n][m])
return num[n][m];
else if(n==1||m==1)
num[n][m]=1;
else if(n>m)
num[n][m]=split(n,m-1)+split(n-m,m);
else if(n<m)
num[n][m]=split(n,n);
else if(n==m)
num[n][m]=split(n,m-1)+1;
return num[n][m];
}