LeetCode/solutions/39. Combination Sum.md
2019-01-07 11:19:17 +08:00

47 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [39. Combination Sum](https://leetcode.com/problems/combination-sum/)
# 思路
题意从一个无重复元素的数组里面选一些数字出来使这些数字的和恰好为target数组里的数字可以重复使用。
就是一个回溯题类似DFS另外为了避免得到重复结果先对数组进行排序常规操作
为了进行递归调用我们定义了一个函数helper传入的参数有
* nums - 当前被选中的数
* candidates - 就是题意里面的数组(从小到大排序好的)
* start - 只能考虑数组candidates下标为start及后面的数
* curr_target - 当前的目标我们希望的就是nums的元素和加上curr_target就等于target
helper函数定义如下
* 当`curr_target == 0`时说明nums的元素和就等于targetnums就是一组我们要求的数push进结果数组即可。
* 当`start >= candidates.size()`时说明start已经超过了candidates最大下标返回即可
* 当`candidates[start] > curr_target`时说明candidates中当前可用的最小的数都比curr_target大也是直接返回。
* 前面三个条件都不满足时,就有两条路要走:
1. 将candidates[start]加入到nums中令`curr_target = curr_target - candidates[start]`, 进入下一层递归;
2. 不将candidates[start]加入到nums中, 令`start + 1`,进入下一层递归;
# C++
``` C++
class Solution {
private:
vector<vector<int>>res;
void helper(vector<int>& nums, const vector<int>& candidates, const int& start, const int& curr_target){
if(curr_target == 0){
res.push_back(nums);
return;
}
if(start >= candidates.size() || candidates[start] > curr_target) return;
nums.push_back(candidates[start]);
helper(nums, candidates, start, curr_target - candidates[start]);
nums.pop_back();
helper(nums, candidates, start + 1 , curr_target);
return;
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
if(candidates.empty()) return res;
sort(candidates.begin(), candidates.end());
vector<int>nums;
helper(nums, candidates, 0, target);
return res;
}
};
```