codevs 2549 自然数和分解

2549 自然数和分解

题目描述 Description

把自然数N分解为若干个自然数之和,输出方案数。

输入描述 Input Description

N,(1≤n≤50)

输出描述 Output Description

方案数

样例输入 Sample Input

5

样例输出 Sample Output

7

数据范围及提示 Data Size & Hint

5 可分为

1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3

#include<cstdio>
using namespace std;
int a[100]={1},n,s;
void cf(int x,int y)
{
	int i;
	for(i=a[y-1];i<=x;i++)
	  if(i<=n)
	  {
	  	  a[y]=i;
	  	  x-=i;//减去数i,再继续拆分x
	  	  if(x==0)//拆分结束
	  	    s++;//累加方案数
	  	  else
	  	    cf(x,y+1);
	  	  x+=i;//回溯,以便可以产生所有可能的情况
	  }
}
int main()
{
	scanf("%d",&n);
	cf(n,1);
	printf("%d",s);
	return 0;
}

类题练习:洛谷 p2404

原文地址:https://www.cnblogs.com/jyhywh/p/5573675.html