Combination Sum
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]
思路:典型的DSF题目,对每一个元素进行选择,是否需要加入。该题目中每个元素可以出现多次。因此每个元素可以多次选择。
- public void combinationSumHelper(ArrayList<ArrayList<Integer> > res, ArrayList<Integer> cur,int[] candidates,int target,int start,int end) {
- if(target <= 0) {
- if(target == 0) {
- res.add(new ArrayList<Integer>(cur)); // must add the object
- }
- return ;
- }
- for(int i=start;i<=end;i++) {
- cur.add(candidates[i]);
- combinationSumHelper(res,cur,candidates,target-candidates[i],i,end);
- cur.remove(cur.size()-1);
- }
- }
- public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
- ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer> >();
- if(candidates==null || candidates.length==0) return res;
- Arrays.sort(candidates);
- ArrayList<Integer> cur = new ArrayList<Integer>();
- combinationSumHelper(res,cur,candidates,target,0,candidates.length-1);
- return res;
- }
改进: 如果从当前值开始遍历,且当前值>start,且当前值 == 前一个值,则表明该值已经遍历完毕,可以直接进行下一个。
- vector<vector<int> > res;
- void combinationsSumHelper(vector<int> &candidates, int target,vector<int> &cur,int start) {
- if(start>=candidates.size() || target<=0) {
- if(target==0) {
- res.push_back(cur);
- }
- return;
- }
- for(int i=start;i<candidates.size();i++) {
- if(i>start && candidates[i]==candidates[i-1]) continue;
- cur.push_back(candidates[i]);
- combinationsSumHelper(candidates,target-candidates[i],cur,i);
- cur.pop_back();
- }
- }
- vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
- int vsz = candidates.size();
- if(vsz==0) return res;
- sort(candidates.begin(),candidates.end());
- vector<int> cur;
- combinationsSumHelper(candidates,target,cur,0);
- return res;
- }

浙公网安备 33010602011771号