Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7
and target 7
,
A solution set is: [7]
[2, 2, 3]
解题思路:
使用回溯的思想穷举可能的结果。
代码:
1 class Solution { 2 public: 3 vector<vector<int>> combinationSum(vector<int>& candidates, int target) { 4 vector<vector<int>> lst; 5 vector<int> ans; 6 sort(candidates.begin(), candidates.end()); 7 Backtracking(lst, ans, candidates, 0, target); 8 return lst; 9 } 10 11 void Backtracking(vector<vector<int>> &lst, vector<int> ans, vector<int> candidates, int idx, int left) { 12 for (int i = idx; i < candidates.size(); ++i) { 13 int cur_left = left - candidates[i]; 14 if (cur_left == 0) { 15 ans.push_back(candidates[i]); 16 lst.push_back(ans); 17 return; 18 } 19 if (cur_left > 0) { 20 ans.push_back(candidates[i]); 21 Backtracking(lst, ans, candidates, i, cur_left); 22 ans.pop_back(); 23 } else { 24 return; 25 } 26 } 27 } 28 };
另:是否还有DP/DFS等其他思路。