Combination Sum
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]
思路:
常见的回溯问题
我的代码:
public class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { if(candidates == null || candidates.length == 0) return rst; List<Integer> list = new ArrayList<Integer>(); Arrays.sort(candidates); helper(list, candidates, target, 0, 0); return rst; } private List<List<Integer>> rst = new ArrayList<List<Integer>>(); public void helper(List<Integer> list, int[] candidates, int target, int sum, int start) { if(sum > target) return; if(sum == target) { if(!rst.contains(list)) rst.add(new ArrayList(list)); return; } for(int i = start ; i < candidates.length; i++) { list.add(candidates[i]); helper(list, candidates, target, sum + candidates[i], i); list.remove(list.size() - 1); } } }
posted on 2015-03-10 16:16 zhouzhou0615 阅读(160) 评论(0) 编辑 收藏 举报