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
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
一个简单的递归搜素,但是关键点在于组合问题,也就是用for(i = 0;i < n;i++)这种从0开始的搜索会出错。
代码:
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<stdio.h>
using namespace std;
int t,n;
int array[13];
int temp[13];
bool visited[13];
int flag;
int cmp(int a,int b)
{
if(a > b)
return 1;
else
return 0;
}
void DFS(int count,int k,int x)
{
if(count == t)
{
flag = 1;
for(int i = 0;i < k - 1;i++)
{
cout<<temp[i]<<"+";
}
cout<<temp[k-1]<<endl;
return;
}
for(int j = x;j < n;j++)
{
if(count + array[j] <= t)
{
temp[k] = array[j];
DFS(count + array[j],k+1,j+1);
while(j + 1 < n&&array[j+1] == array[j])
j++;
}
}
}
int main()
{
int i,j,k;
while(~scanf("%d%d",&t,&n))
{
flag = 0;
if(n == 0)
break;
memset(visited,false,sizeof(visited));
for(i = 0;i < n;i++)
{
scanf("%d",&array[i]);
}
sort(array,array+n,cmp);
cout<<"Sums of "<<t<<":"<<endl;
DFS(0,0,0);
if(!flag)
cout<<"NONE"<<endl;
}
return 0;
}