有n个数,输出其中所有和为s的k个数的组合。

分析:此题有两个坑,一是这里的n个数是任意给定的,不一定是:1,2,3...n,所以可能有重复的数(如果有重复的数怎么处理?);二是不要求你输出所有和为s的全部组合,而只要求输出和为s的k个数的组合。

举个例子,假定n=6,这6个数为:1 2 1 3 0 1,如果要求输出和为3的全部组合的话,

  • 1 2
  • 1 2 0
  • 0 3
  • 1 1 1
  • 1 1 1 0

而题目加了个限制条件,若令k=2,则只要求输出:[{1,2}, {0,3}] 即可。

#include <iostream>
#include<list>
#include<vector>
using namespace std;

#define SUM 20
#define SIZE 10
#define K 3
#define HASHSIZE 9

list<int> mylist;
vector<int> hashvector;

void initRandom(int* arr) {
	srand(unsigned(time(0)));
	for (int i = 0; i < SIZE; i++) {
		arr[i] = rand() % 10;
	}

	for (int i = 0; i < SIZE; i++) {
		cout << " " << arr[i];
	}
	cout << endl;
}

int getCurHash() {
	int hash = 0;
	for (list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it) {
		hash |= (1 << *it);
	}
	return hash;
}

void sumOfkNum(int sum, int*arr, int i, bool &flag) {
	if (sum <= 0 || i == SIZE) {
		return;
	}
	if (sum == arr[i] && mylist.size() == K - 1) {
		int hash = getCurHash() | (1 << arr[i]);

		if (find(hashvector.begin(), hashvector.end(), hash)
				== hashvector.end()) {
			hashvector.push_back(hash);
			for (list<int>::iterator it = mylist.begin(); it != mylist.end();
					++it) {
				cout << *it << "+";
			}
			cout << arr[i] << endl;
		} else {
			return;
		}
	} else {
		if (mylist.size() > K) {
			return;
		}
		mylist.push_back(arr[i]);
		sumOfkNum(sum - arr[i], arr, i + 1, flag);
		mylist.pop_back();
		sumOfkNum(sum, arr, i + 1, flag);
	}
}

int main() {
	int* arr = new int[SIZE];
	bool flag = false;
	initRandom(arr);
	sumOfkNum(SUM, arr, 0, flag);
	if (hashvector.empty()) {
		cout << "no result" << endl;
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值