借鉴了:https://blog.csdn.net/henu111/article/details/87857978
7-195 整数分解为若干项之和
将一个正整数N分解成几个正整数相加,可以有多种分解方法,例如7=6+1,7=5+2,7=5+1+1,…。编程求出正整数N的所有整数分解式子。
输入格式:
每个输入包含一个测试用例,即正整数N (0<N≤30)。
输出格式:

输入样例:
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;7=7
得亏看到了借鉴那位的博客,不然我都要打表写了😅
学到了这种题目可以用dfs写,这里有一点要注意就是输出的式子一定是递增的,不会出现4=1+2+1这种情况
AC代码:
#include<bits/stdc++.h>
using namespace std;
#define endl "\n"
int a[35];
int cnt=0;
void dfs(int num,int n,int pos,int sum) //分别表示当前值,需要达到的值,当前位置,当前和
{
if (sum == n)
{
cnt++;
cout << n << "=";
for (int i = 1; i < pos; i++)
{
cout << a[i];
if (i < pos-1) cout << '+';
}
if (cnt % 4 == 0 || pos == 2) cout << endl;
else cout << ";";
return;
}
else if (sum > n) return;
for (int i = num; i <= n; i++)
{
a[pos] = i;
dfs(i, n, pos + 1, sum + i);
}
}
int main()
{
int n;
cin >> n;
dfs(1, n, 1, 0);
}✳
谢谢你读到这里。
更新于 2022-08-11