给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
示例 1:
输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
示例 2:
输入: candidates = [2,3,5], target = 8,
所求解集为:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
这个题和PathSum这类题类似,所以思路这次采用递归,用深度搜索的方式来找到所有的集合,方法直接从代码看就可以,这里说一下python浅复制和深复制,用等于号和copy都是浅复制,深复制的方法是copy.deepcopy(name),只有这样才算是深度复制,否则都是相当于一个引用,改变name值时另一个被赋值的值也会跟着改。
C++源代码:
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
sort(candidates.begin(), candidates.end());
combinationSumDFS(candidates, target, 0, {}, res);
return res;
}
void combinationSumDFS(vector<int>& candidates, int target, int start, vector<int> out, vector<vector<int>>& res)
{
if(target < 0) return;
else if(target == 0)
{
res.push_back(out);
return;
}
for(int i=start;i<candidates.size();i++)
{
out.push_back(candidates[i]);
combinationSumDFS(candidates, target-candidates[i], i, out, res);
out.pop_back();
}
}
};
python3源代码:
class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
out = []
candidates.sort()
self.combinationSumDFS(candidates, target, 0, out, res)
return res
def combinationSumDFS(self, candidates, target, start, out, res):
if target < 0:
return
elif target == 0:
res.append(copy.deepcopy(out))
return
for i in range(start, len(candidates)):
out.append(candidates[i])
self.combinationSumDFS(candidates, target-candidates[i], i, out, res)
out.pop()