Combination Sum II:
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set
A solution set is:
[10, 1, 2, 7, 6, 1, 5]
and target 8
, A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]Combination Sum III:
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.
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]]
[Thoughts]
Similar to "Combination Sum", those are just variations. The same code skeleton of backtracking on a vector can be reused. The variations are marked in the following code.
[Solution]
//-- Combination Sum II --
class Solution {
void backtrack(vector<int>& cand, int target, int start, vector<int>& tmplist, vector<vector<int>>& res) {
if (target<0) return;
if (target==0) {
res.push_back(tmplist); return;
}
for (int i=start; i<cand.size();i++) {
tmplist.push_back(cand[i]);
backtrack(cand, target-cand[i], i+1, tmplist, res);
tmplist.pop_back();
while(cand[i+1]==cand[i]) i++; //skip duplicates
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> sublist;
sort(candidates.begin(), candidates.end());
backtrack(candidates, target, 0, sublist, res);
return res;
}
};
//-- Combination Sum III --
class Solution {
void backtrack(int len, int target, int start, vector<int>&tmplist, vector<vector<int>>& res) {
if (target<0) return;
if (target==0 && tmplist.size()==len) {
res.push_back(tmplist); return;
}
if (tmplist.size()>len) return; // length limit
for (int i=start; i<10; i++) {
tmplist.push_back(i);
backtrack(len, target-i, i+1, tmplist, res);
tmplist.pop_back();
}
}
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> res;
vector<int> tmplist;
backtrack(k, n, 1, tmplist, res);
return res;
}
};
No comments:
Post a Comment