判重哈希表解决:
#include <iostream>
using namespace std;
const int nMax = 15;
const int INF = 10007;
int t, n;
int A[nMax];
int flag;
int hash[INF][15];
int head[INF];
//int head[], next[];
//int ans[nMax];
//int len;
bool isSame(int *a, int *b, int len)
{
if(a[0] != len)
return 0;
int i;
for(i = 0; i < len; ++ i)
if(a[1 + i] != b[i])
return 0;
return 1;
}
int insert(int *ans, int len)
{
int k = 0;
int i;
for(i = 0; i < len; ++ i)
k = (k * 10 + ans[i]) % INF;
while(head[k] != 0 && !isSame(hash[k], ans, len))
{
k ++;
k %= INF;
}
if(head[k] == 0)
{
head[k] = 1;
hash[k][0] = len;
memcpy(hash[k] + 1, ans, len * sizeof(int));//memcpy最后的长度最后能够自己定义出来
return 1;
}
return 0;
}
void dfs(int pos, int m, int *ans, int len)
{
if(pos >= n)
return;
if(A[pos] <= m)
{
ans[len] = A[pos];
if(A[pos] == m)
{
flag = 1;
if(insert(ans, len + 1))//这里的len需要加1来保证程序的正常判断
{
int i;
for(i = 0; i <= len; ++ i)
{
if(i)
printf("+");
printf("%d", ans[i]);
}
printf("\n");
}
}
else
dfs(pos + 1, m - A[pos], ans, len + 1);
}
/*
int p = pos + 1;
while(A[p] == A[pos])
p ++;
*/
dfs(pos + 1, m, ans, len);
}
int main()
{
//freopen("e://data.in", "r", stdin);
while(scanf("%d%d", &t, &n) != EOF)
{
if(n == 0)
break;
int i;
for(i = 0; i < n; ++ i)
scanf("%d", &A[i]);
int ans[nMax];
flag = 0;
printf("Sums of %d:\n", t);
dfs(0, t, ans, 0);
if(flag == 0)
printf("NONE\n");
}
return 0;
}