0
点赞
收藏
分享

微信扫一扫

自然数的拆分

at小涛 2024-08-17 阅读 40

 

自然数的拆分

题目描述

任何一个大于1的自然数n,总可以拆分成若干个小于n的自然数之和。
即n=s[1]+s[2]+……+s[k]的形式,且s[1]<=s[2]<=s[3]<=……<=s[k]
请按字典序输出。

输入格式

待拆分的自然数n(n<=20)

输出格式

若干数的加法式子。

样例输入1

7

样例输出1

1+1+1+1+1+1+1
1+1+1+1+1+2
1+1+1+1+3
1+1+1+2+2
1+1+1+4
1+1+2+3
1+1+5
1+2+2+2
1+2+4
1+3+3
1+6
2+2+3
2+5
3+4
7
total=15

#include<bits/stdc++.h>
using namespace std;
int n,a[25]={1},total;
void dfs(int d,int h){
//	printf("%d %d \n",d,h);
	if(h==n){
		d--;
		total++;
		printf("%d",a[1]);
		for(int i=2;i<=d;i++)printf("+%d",a[i]);puts(" ");
		return ;
	}
	if(h>n)return;
	for(int i=a[d-1];i+h<=n;i++){
		a[d]=i;
		dfs(d+1,h+i);
	}
}
int main(){
	cin>>n;
	dfs(1,0);
	printf("total=%d\n",total);
} 
举报

相关推荐

0 条评论