Leetcode|Combination Sum III[回溯]
阿新 • • 發佈:2018-11-14
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Ensure that numbers within the set are sorted in ascending order.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
解法1: 4ms
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<int> candidates={1,2,3,4,5,6,7,8,9};
vector<int> temp;
vector<vector<int >> res;
combinationSum(candidates,0,n,temp,res,k);
return res;
}
void combinationSum(vector<int>& candidates,int index,int target,vector<int> temp,vector<vector<int>> &res, int k){
if(index==candidates.size()||candidates[index]>target||temp.size()>=k) return ;//終止條件
temp.push_back(candidates[index]);
if(candidates[index]==target&&temp.size()==k){
res.push_back(temp);//找到一組滿足條件的
return;
}
combinationSum(candidates,index+1,target-candidates[index],temp,res,k);
temp.pop_back();
combinationSum(candidates,index+1,target,temp,res,k);
}
};
解法2:0ms 加個for迴圈協助遞迴。
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<int> candidates={1,2,3,4,5,6,7,8,9};
vector<int> temp;
vector<vector<int>> res;
combinationSum(candidates,0,n,temp,res,k);
return res;
}
void combinationSum(vector<int>& candidates,int index,int target,vector<int> temp,vector<vector<int>> &res, int k){
if(index==candidates.size()||candidates[index]>target||temp.size()>=k) return;//終止條件
for(int i=index;i<candidates.size();i++){
temp.push_back(candidates[i]);
if(candidates[i]==target&&temp.size()==k){
res.push_back(temp);//找到一組滿足條件的
return;
}
combinationSum(candidates,i+1,target-candidates[i],temp,res,k);
temp.pop_back();
}
//combinationSum(candidates,index+1,target,temp,res,k);
}
};