leetcode中常见的backTrack类题目:combination、subsets、permutation、Palindrome Partitioning.
1、combination
<1>leetcode39. Combination Sum
题目描述:
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
target
) will be positive integers.Input: candidates =[10,1,2,7,6,1,5]
, target =8
, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
Input: candidates = [2,5,2,1,2], target = 5, A solution set is: [ [1,2,2], [5] ]
void backTrack(vector<vector<int>>& ans, vector<int>& tmp, const vector<int>& nums, int remain, int start){
if(remain < 0) return;
else if(remain == 0) ans.push_back(tmp);
else{
for(int i = start; i < nums.size(); i++){
tmp.push_back(nums[i]);
backTrack(ans, tmp, nums, remain - nums[i], i);
tmp.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int>& nums, int target){
vector<vector<int>> ans;
vetcot<int> temp;
sort(nums.begin(), nums.end());
backTrack(ans, temp, nums, target, 0);
return ans;
}
<2>leetcode40. Combination Sum I
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
target
) will be positive integers.Input: candidates =[10,1,2,7,6,1,5]
, target =8
, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
Input: candidates = [2,5,2,1,2], target = 5, A solution set is: [ [1,2,2], [5] ]
void backTrack(vector<vector<int>>& ans, vector<int>& tmp, const vector<int>& nums, int remain, int step){
if(remain < 0) return;
else if(remain == 0) ans.push_back(tmp);
else{
for(int i = step; i < nums.size(); i++){
if(i > step && nums[i - 1] == nums[i]) continue;
tmp.push_back(nums[i]);
backTrack(ans, tmp, nums, remain - nums[i], i + 1);
tmp.pop_back();
}
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> tmp;
sort(candidates.begin(), candidates.end());
backTrack(ans, tmp, candidates, target, 0);
return ans;
}