Combination Sum
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.
Note:
- All numbers (including target) will be positive integers.
- 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)最主要的是防止重复,所以,当某个数小于target时,将数放入list中,下一次对该list进行添加时,只能添加大于或等于该数的值,这样就能够避免说重复。 (2)就是每次将某个数添加到list中时,要让target减去相应的值作为新的target。 (3)针对(1)我们可以筛选,当当前的数大于target/2时,不添加到list中。 (4)当当前的值 == target时,添加到list中,并将该list添加到result中。public class Solution { private List<List<Integer>> result = new ArrayList<List<Integer>>(); public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); findanswer(0,new ArrayList<Integer>(),candidates,target); return result; } public void findanswer(int index,List<Integer>ans,int[] candidates,int target) { while(index < candidates.length && candidates[index]<= target) { //添加该数,并更新target if(candidates[index] <= target/2) { List<Integer> l1 = new ArrayList<Integer>(ans); l1.add(candidates[index]); findanswer(index,l1,candidates,target-candidates[index]); } //找到满足条件的,更新list,并添加到result中 if(candidates[index] == target) { List<Integer> l1 = new ArrayList<Integer>(ans); l1.add(candidates[index]); result.add(l1); } index++; } } }