标签:des style blog color io os ar for sp
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. 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 10,1,2,7,6,1,5 and target 8, A solution set is: [1, 7] [1, 2, 5] [2, 6] [1, 1, 6]
NP问题,遇到很多次了,这道题跟Combination Sum很像
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) { 3 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 4 if (num == null || num.length == 0) return res; 5 ArrayList<Integer> path = new ArrayList<Integer>(); 6 Arrays.sort(num); 7 helper(res, path, num, target, 0, 0); 8 return res; 9 } 10 11 public void helper(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> path, int[] num, int target, int accum, int index) { 12 if (accum > target) return; 13 if (accum == target) { 14 if (!res.contains(path)) res.add(new ArrayList<Integer>(path)); 15 return; 16 } 17 for (int i=index; i<num.length; i++) { 18 path.add(num[i]); 19 helper(res, path, num, target, accum+num[i], i+1); 20 path.remove(path.size()-1); 21 } 22 } 23 }
CodeGanker的做法:注意21行他处理重复的情况,直接跳过
1 public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) { 2 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 3 if(num == null || num.length==0) 4 return res; 5 Arrays.sort(num); 6 helper(num,0,target,new ArrayList<Integer>(),res); 7 return res; 8 } 9 private void helper(int[] num, int start, int target, ArrayList<Integer> item, 10 ArrayList<ArrayList<Integer>> res) 11 { 12 if(target == 0) 13 { 14 res.add(new ArrayList<Integer>(item)); 15 return; 16 } 17 if(target<0 || start>=num.length) 18 return; 19 for(int i=start;i<num.length;i++) 20 { 21 if(i>start && num[i]==num[i-1]) continue; 22 item.add(num[i]); 23 helper(num,i+1,target-num[i],item,res); 24 item.remove(item.size()-1); 25 } 26 }
标签:des style blog color io os ar for sp
原文地址:http://www.cnblogs.com/EdwardLiu/p/4008102.html