有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
    评论
好的,我可以帮你解决这个问题。 我们可以先对列表进行排序,然后使用三个指针 i、j、k 分别表示三个数的下标。初始时,i 指向列表的第一个元素,j 指向 i 的后一个元素,k 指向列表的最后一个元素。然后,我们不断移动指针,直到找到三个数之和为 100 的组合为止。具体实现可以参考以下代码: ```python def find_combinations(lst): lst.sort() # 先对列表进行排序 n = len(lst) res = [] for i in range(n - 2): # i 从第一个数开始遍历到倒数第三个数 if i > 0 and lst[i] == lst[i-1]: continue # 如果与前一个数相同,直接跳过,避免重复 j, k = i + 1, n - 1 # j 和 k 初始分别指向 i 的后一个数和列表的最后一个数 while j < k: s = lst[i] + lst[j] + lst[k] if s == 100: res.append((lst[i], lst[j], lst[k])) j += 1 k -= 1 while j < k and lst[j] == lst[j-1]: j += 1 # 如果与前一个数相同,直接跳过,避免重复 while j < k and lst[k] == lst[k+1]: k -= 1 # 如果与后一个数相同,直接跳过,避免重复 elif s < 100: j += 1 # 如果三个数之和小于 100,让 j 右移 else: k -= 1 # 如果三个数之和大于 100,让 k 左移 return res ``` 你可以将列表作为参数传入 `find_combinations` 函数,它会返回所有三个数之和为 100 的不重复组合。例如: ```python lst = [1, 2, 3, 4, 5, 95, 96, 97, 98, 99] res = find_combinations(lst) print(res) # 输出 [(1, 2, 97), (1, 3, 96), (1, 4, 95), (2, 3, 95)] ``` 希望对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值