Given a set of candidate numbers (C) (without duplicates) 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.输入一个不含重复数字的候选的数字集(C)和一个目标数字(T)。咱们须要找出c中的数字的不一样组合,使得每一种组合的元素加和为T。code
For example, 输入的候选集[2, 3, 6, 7]和目标数字7,
结果集是:
[[7],[2, 2, 3]]递归
public List<List<Integer>> combinationSum(int[] nums, int target) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(nums); backtrack(res,new ArrayList<>(),nums,target,0); return res; } public void backtrack(List<List<Integer>> res,List<Integer> temp,int[] nums,int remain,int start){ if(remain <0)return; if(remain == 0)res.add(new ArrayList<>(temp)); else{ for(int i=start;i<nums.length;i++){ temp.add(nums[i]); backtrack(res,temp,nums,remain-nums[i],i); temp.remove(temp.size()-1); } } }