Combination Sum II
这道题比Combination Sum还要简单,因为每个数不能重复使用,所以只需要从下一个开始即可,和subset II一样
public class Solution { /** * @param num: Given the candidate numbers * @param target: Given the target number * @return: All the combinations that sum to target */ public List<List<Integer>> combinationSum2(int[] num, int target) { // write your code here List<List<Integer>> result = new ArrayList<List<Integer>>(); if(num.length == 0 || num == null){ return result; } List<Integer> list = new ArrayList<Integer>(); Arrays.sort(num); helper(result, list, num, target, 0); return result; } private void helper(List<List<Integer>> result, List<Integer> list, int[] num, int target, int pos){ if (target == 0){ result.add(new ArrayList<Integer>(list)); } for(int i = pos; i < num.length; i++){ if (num[i] > target){ break; } if (i > pos && num[i] == num[i-1]){ continue; } list.add(num[i]); helper(result, list, num, target - num[i], i+1); list.remove(list.size() - 1); } } }
posted on 2016-08-18 08:47 codingEskimo 阅读(141) 评论(0) 编辑 收藏 举报