关于自然数拆分问题的讨论
题目如下
Description
任何一个大于1的自然数n,总可以拆分成若干个小于n的自然数之和。
Input
输入有多组数据,对于每组数据就一个数n。
Output
对于每组输入输出n的拆分方法。
Sample Input
4
7
Sample Output
4=1+1+1+1
4=1+1+2
4=1+3
4=2+2
total=4
7=1+1+1+1+1+1+1
7=1+1+1+1+1+2
7=1+1+1+1+3
7=1+1+1+2+2
7=1+1+1+4
7=1+1+2+3
7=1+1+5
7=1+2+2+2
7=1+2+4
7=1+3+3
7=1+6
7=2+2+3
7=2+5
7=3+4
total=14
对于我而言吧,本体看似简单,毕竟这是一道高中的数学题
但是要用dfs来模拟这个问题的话,确实挺复杂的,毕竟对于我萌新而言,三个参数的dfs想不到,还好有学长知道,多谢flc学长啦
下面是我对此题的理解和解决方案
ACcode
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<cctype>
using namespace std;
const int N = 1e5+10;
int ans[N],res;
int n;
void dfs(int k,int cnt/*数量*/,int last/*最后一个数*/)
{
int i;
if(last!=0) ans[cnt]=last;//如果最后一个数字不为0,那么取出这个数字
if(k==0&&ans[1]!=n)//如果最开始的n的数值变成了0;并且取出的第一个数不是n,那么输出该数字(输出没有n=n的情况)
{
//下面是输出的情况
printf("%d=%d",n,ans[1]);//输出第一个数
for(i=2;i<=cnt;i++)
printf("+%d",ans[i]);//输出下面的数
printf("\n");
res++;//结果加一,dfs的常规套路
return ;
}
//i=max(last,1),这个则是对于最后一个数与1的比较
for(i=max(last,1);i<=k;i++)
{
dfs(k-i,cnt+1,i);//这一步比较绕,就是递归剩下k-i,数量cnt+1,以及最后一位数i;
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
res=0;
dfs(n,0,0);//递归初始last==0,数量cnt==0,并且k==n;
printf("total=%d\n",res);
}
return 0;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。