标题: | |
通过率: | 27.7% |
难度: | 中等 |
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
,
[7]
[2, 2, 3]
本题依然是递归算法,算法的关键点是递归时重复元素。题目上说可以从candidate中重复一个元素,那么再递归时不用从i+1开始,还是从i开始,结果还可能是重复的情况,那么还是要res。cantain一次,具体细节看代码:
1 public class Solution { 2 public ArrayList> combinationSum(int[] candidates, int target) { 3 ArrayList > res=new ArrayList >(); 4 ArrayList tmp=new ArrayList (); 5 Arrays.sort(candidates); 6 dfs(candidates,target,0,res,tmp); 7 return res; 8 } 9 public void dfs(int[] candidates, int target,int start,ArrayList > res,ArrayList tmp){10 if(target<0)return;11 if(target==0 && !res.contains(tmp)){12 res.add(new ArrayList (tmp));13 return ;14 }15 for(int i=start;i