HOJ 1258 Sum It Up

这一题用dfs进行求解,去重比较关键

#include<iostream>
#include<algorithm>
using namespace std;
int t, n, a[12], b[12];//t为求和数,n为一组数的个数,a为这一组数,b存储符合要求的数
bool flag;//判断是否有解

int cmp(int a, int b) {
	return a > b;
}

void dfs(int sum, int ai, int bi) {//和,当前a数组的操作位置,b数组的操作位置
	if (sum > t) return;
	if (sum == t) {
		flag = true;
		cout << b[0];
		for (int i = 1; i < bi; i++)
			cout << "+" << b[i];
		cout << endl;
		return;
	}
	for (int i = ai; i < n; i++) {
		b[bi] = a[i];
		dfs(sum + a[i], i + 1, bi + 1);
		while (i + 1 < n && a[i] == a[i + 1]) i++;
		//进行去重操作,对相同的数不能重复进行
		//难点:区别理解一个和式中和为4是可以输出1+1+1+1的
	}
}

int main() {
	int t;
	while ((cin >> t >> n) && t != 0 && n != 0) {
		flag = false;
		for (int i = 0; i < n; i++)
			cin >> a[i];
		while (a[0] > t
			) {
			for (int i = 0; i < n - 1; i++)
				a[i] = a[i + 1];
			n--;
		}
		cout << "Sums of " << t << ":" << endl;
		dfs(0, 0, 0);
		if (flag == false) cout << "NONE" << endl;
	}
	return 0;
}
发布了7 篇原创文章 · 获赞 0 · 访问量 34

猜你喜欢

转载自blog.csdn.net/qq_44724908/article/details/103973044