将一个正整数N分解成几个正整数相加,可以有多种分解方法,例如7=6+1,7=5+2,7=5+1+1,…。编程求出正整数N的所有整数分解式子。
代码实现:
#include<iostream>
using namespace std;
int a[31], sum, cnt, top = -1;
void f(int i, int n)
{
int k, j;
if(sum == n)
{
cnt++;
cout<<n<<"=";
for(k = 0; k < top; k++)
cout<<a[k]<<"+";
if(cnt % 4 == 0 || a[top] == n)
cout<<a[top]<<endl;
else cout<<a[top]<<";";
return ;
}
if(sum > n) return ;
for(j = i; j <= n; j++)
{
a[++top] = j;
sum += j;
f(j, n);
sum -= j;//回溯
top--;//回溯
}
}
int main()
{
int n;
cin>>n;
f(1, n);
return 0;
}