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:
2,3,6,7
and target
7
,
[7]
[2, 2, 3]
public class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(candidates); Stack<Integer> stack = new Stack<Integer>(); dfs(res, stack, target, 0, candidates,0); return res; } void dfs(List<List<Integer>> res,Stack<Integer> stack,int target,int cur,int[] arr,int sum){ if(sum==target){ ArrayList<Integer> data = new ArrayList<Integer>(stack); res.add(data); return; }else if(sum>target) return; else{ for(int i=cur;i<arr.length;i++){ stack.add(arr[i]); sum += arr[i]; dfs(res, stack, target, i, arr,sum); sum -= arr[i]; stack.pop(); } } } }