自然数的拆分

#include<iostream>
using namespace std;
int ans[10001];
int n;
int total = 0;
void dfs(int s, int dep) {
	if (s == 0) {
		total++;
		cout << n<<'='<<ans[1];
		for (int i = 2; i < dep; i++)
			cout << '+' << ans[i];
		cout << endl;
	}
	for (int i = ans[dep-1]; i < n; i++) {
		if (s - i >= 0) {
			ans[dep] = i;
			dfs(s - i, dep + 1);
		}
	}
}
int main()
{
	ans[0] = 1;
	cin >> n;
	dfs(n,1);
	cout << total;
	return 0;
}

输入7
输出

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
14

变形:n个苹果放r个盘,允许有空盘

#include<iostream>
using namespace std;
int ans[10001];
int t, n, r;//n个苹果放r个盘,允许有空盘
int total = 0;//放置种类
void dfs(int s, int dep) {
	if (s == 0&&dep<=r+1) {
		total++;
		cout << n << '=' << ans[1];
		for (int i = 2; i < dep; i++)
			cout << '+' << ans[i];
		cout << endl;
	}
	for (int i = ans[dep - 1]; i <= n; i++) {
		if (s - i >= 0) {
			ans[dep] = i;
			dfs(s - i, dep + 1);
		}
	}
}
int main()
{
	cin >> t;//数据组数
	ans[0] = 1;
	while (t--) {
		cin >> n>>r;
		dfs(n, 1);
	}
	cout << total;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值