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 void com(vector<int> &candidates,int start,int sum,int target,vector<int> &path,vector<vector<int> > &res) 4 { 5 if(sum>target) 6 return ; 7 if(sum==target) 8 { 9 res.push_back(path); 10 return ; 11 } 12 13 int len=candidates.size(); 14 for(int i=start;i<len;i++) 15 { 16 path.push_back(candidates[i]); 17 com(candidates,i,sum+candidates[i],target,path,res); 18 path.pop_back(); 19 } 20 } 21 22 vector<vector<int> > combinationSum(vector<int>& candidates, int target) { 23 sort(candidates.begin(),candidates.end()); 24 vector<vector<int> > res; 25 vector<int> path; 26 com(candidates,0,0,target,path,res); 27 return res; 28 } 29 };
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.
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 class Solution { 2 public: 3 vector<vector<int>> combinationSum3(int k, int n) { 4 vector<vector<int> >res; 5 vector<int>item; 6 dfs(k,n,1,item,res); 7 return res; 8 } 9 10 void dfs(int k,int n,int level,vector<int> &item,vector<vector<int> >&res) 11 { 12 if(n<0) return ; 13 if(n==0&&item.size()==k) res.push_back(item); 14 for(int i=level;i<=9;i++) 15 { 16 item.push_back(i); 17 dfs(k,n-i,i+1,item,res); 18 item.pop_back(); 19 } 20 } 21 };
[[1,2,6], [1,3,5], [2,3,4]]