【LeetCode】39. Combination Sum

题目:

Given a set of candidate numbers (candidates(without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

描述:

给出一个无重复元素的数组和一个目标值,数组中的元素之间相加可以得到目标值,求所有的解

其中数组中元素全为正数

 

分析:

其实是一个完全背包,而且要求所有的解的情况,

最直接的思路就是采用递归的方法,直接暴力,时间复杂度是指数级别,很明显,超时了....

本以为有多项式级别解法,结果看别人的解法也是使用暴力搜索....

看来需要优化一下自己的代码...

结果发现,其实只需要改一句,详情在代码里...

 

测试数据:

[48,22,49,24,26,47,33,40,37,39,31,46,36,43,45,34,28,20,29,25,41,32,23]
69
[1,3,4]
4
[2,3,9]
1
[2,3,5]
8
[2,3,6,7]
7

 

代码:(时间复杂度,指数级)

class Solution {
public:
	vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
		sort(candidates.begin(), candidates.end());
		vector<vector<int>> result;

		vector<int> solution;
		findSolution(candidates, target, solution, 0, 0, result);

		return result;
	}

	void findSolution(vector<int>& candidates, int target, vector<int>& solution, int sum, int index, vector<vector<int>> &result) {

		if (sum == target) {
			result.push_back(solution);
			return;
		}

		if (index == candidates.size()) {
			return;
		}

		findSolution(candidates, target, solution, sum, index + 1, result);
        
        // int max_count = target / candidates[index];//超时代码
		int max_count = (target - sum) / candidates[index];
        
		for (int i = 0; i < max_count; ++ i) {
			solution.push_back(candidates[index]);
			sum += candidates[index];
			findSolution(candidates, target, solution, sum, index + 1, result);
		}
		while (max_count--) {
			solution.pop_back();
		}
	}

};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值