题意:给出一个目标数t,个数n,以及n个正整数,求出n个数中可能组成的和等于t. , n个数字可不全用。
Sample Input
4 6 4 3 2 2 1 1 5 3 2 1 1 400 12 50 50 50 50 50 50 25 25 25 25 25 25 0 0
Sample Output
Sums of 4: 4 3+1 2+2 2+1+1 Sums of 5: NONE Sums of 400: 50+50+50+50+50+50+25+25+25+25 50+50+50+50+50+25+25+25+25+25+25
思路:dfs.....没什么说的
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 15;
int num[maxn];
int tmp[maxn];
int m,n;
bool temp;
void dfs( int sum, int index, int cnt )
{
if(sum < 0)
return;
if( sum == 0 )//一种情况
{
temp = 1;//记录 是否输出NONE
for( int i = 0; i < cnt; i++ )
{
if( i == 0 )
{
printf("%d", tmp[i]);
}
else
{
printf("+%d", tmp[i]);
}
}
printf("\n");
return;
}
for( int i = index; i < n; i++ )
{
if( i == index || num[i] != num[i-1] )
{
tmp[cnt] = num[i];
dfs( sum - num[i], i + 1, cnt + 1 );//向后退一个元素计算,递归调用
}
}
}
int main()
{
while( scanf("%d%d", &m, &n) && m &&n )
{
temp = 0;
memset( tmp, 0, sizeof( tmp ) );
for( int i = 0; i < n; i++ )
scanf("%d", &num[i]);
printf("Sums of %d:\n", m);
dfs( m, 0, 0 );
if( temp != 1 )
printf("NONE\n");
}
return 0;
}