Description
将n分成m个大于0的不同数的和,1 2同 2 1 视作相同的划分。
按照字典序输出所有方案。数据保证存在解,即不会出现1+2+...m > n的情况
Input
2个数 n,m(1 <= m <= 10,1 <= n <= 50 )。 1+2+...m > n
Output
按照字典序,输出所有方案。数字之间,用空格划分。
Sample Input
13 3
Sample Output
1 2 10
1 3 9
1 4 8
1 5 7
2 3 8
2 4 7
2 5 6
3 4 6
代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e9;
int a[15];
void dfs(int n,int m,int x,int s)
{
int i;
if(x>m+1||s<0)
return;
if(x==m+1&&s==0)
{
for(i=1;i<m;i++)
{
printf("%d ",a[i]);
}
printf("%d\n",a[m]);
return;
}
for(i=a[x-1]+1;i<=s;i++)
{
a[x]=i;
dfs(n,m,x+1,s-i);
}
return;
}
int main()
{
int j,k,n,m,x,sum,len,t,flag;
scanf("%d%d",&n,&m);
dfs(n,m,1,n);
return 0;
}