#include<stdio.h>
#include<string.h>
#define maxn 100
int used[maxn];
int ans[maxn];
void output(int dep)
{
int i = 0;
for(i=1; i<dep; i++)
{
printf("%d ", ans[i]);
}
printf("\n");
}
void solve(int n, int sum, int cursum, int dep)//cursum初始为0 dep初始为1 ans[dep=0] = 0
{
if(cursum == sum)
{
output(dep);
return;
}
else
{
int i = 0;
for(i=1; i<=n; i++)
{
if(used[i]==0 && ans[dep-1]<i)//不含有相同元素切解中元素递增,因此能得保证解不相同
{
used[i] = 1;
ans[dep] = i;
cursum += i;
dep += 1;
solve(n, sum, cursum, dep);
dep -= 1;
cursum -= i;
ans[dep] = 0;
used[i] = 0;
}
}
}
}
int main()
{
int n, sum;
while(scanf("%d %d", &n, &sum) != EOF)
{
if(n==0) break;
memset(used, 0, sizeof(used));
memset(ans, 0, sizeof(ans));
solve(n, sum, 0, 1);
}
return 0;
}
1-n之间的整数之和为指定数sum问题(百度之星往年试题)
最新推荐文章于 2023-12-10 16:06:49 发布