ZOJ 1711 Sum It Up

#include <iostream>

using namespace std;

const int MAX = 16;
int ans[MAX], num[MAX];
int len, t, n;
bool ok;

void dfs(int cur, int sum, int cnt)
{
	if (sum > t)
		return;
	if (sum == t)
	{
		ok = true;
		cout << ans[0];
		for (int i = 1; i < cnt; i++)
			cout << "+" << ans[i];
		cout << endl;
		return;
	}
	for (int i = cur; i < n; i++)
	{
		if (i == cur || num[i] != num[i - 1])
		{
			ans[cnt] = num[i];
			dfs(i + 1, sum + num[i], cnt + 1);
		}
	}
}

int main()
{
	while (cin >> t >> n, n)
	{
		len = 0;
		ok = false;
		for (int i = 0; i < n; i++)
			cin >> num[i];
		cout << "Sums of " << t << ":" << endl;
		dfs(0, 0, 0);
		if (ok == false)
			cout << "NONE" << endl;
	}
}

你可能感兴趣的:(ZOJ 1711 Sum It Up)