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]
]
题目大意:
给一个不重复的数组,寻找数组中数字的排列组合,使得这个排列组合之和等于target。数组中的数字可以重复使用,找到数组中全部的排列组合。
解法:
我首先想到的是回溯法,首先对数组中的数进行排序,tmp数组记录当前排列组合,tmpSum记录当前排列组合之和,index记录遍历到数组哪一个数了。
C++:
class Solution {
private:
void combinationCore(vector<int>&candidates,int index,int tmpSum,int target,vector<int>&tmp,vector<vector<int>>&res){
if(tmpSum>target) return;
if(tmpSum==target) {
res.push_back(tmp);
return;
}
for(int i=index;i<candidates.size();i++){
tmpSum+=candidates[i];
tmp.push_back(candidates[i]);
combinationCore(candidates,i,tmpSum,target,tmp,res);
tmpSum-=candidates[i];
tmp.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>>res;
vector<int>tmp;
sort(candidates.begin(),candidates.end());
combinationCore(candidates,0,0,target,tmp,res);
return res;
}
};
其实自己写的代码有点冗余,其中的tmpSum可以不需要,直接使用target减去值,再和零进行比较,递归调用的时候也是。可以参考下面的python代码。
Python:
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res=[]
candidates.sort()
self.dfs(candidates,target,0,[],res)
return res
def dfs(self,candidates,target,index,path,res):
if target<0:
return
if target==0:
res.append(path)
return
for i in range(index,len(candidates)):
self.dfs(candidates,target-candidates[i],i,path+[candidates[i]],res)
写上面的代码发现python中的list进行合并可以采用[]+[]
range(start,end)返回的列表并不包括end