标签:leetcode java algorithms datastructure np
public class Solution { public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) { ArrayList<ArrayList<Integer>> results=new ArrayList<ArrayList<Integer>>(); if(candidates==null) return results; Arrays.sort(candidates); helper(candidates,0,target,results,new ArrayList<Integer>()); return results; } private void helper(int[] candidates,int start,int target,ArrayList<ArrayList<Integer>> results,ArrayList<Integer> temp){ if(target==0){ results.add(new ArrayList<Integer>(temp)); return; } for(int i=start;i<candidates.length;i++){ if(candidates[i]<=target){ temp.add(candidates[i]); helper(candidates,i,target-candidates[i],results,temp); temp.remove(temp.size()-1); } } } }
public class Solution { public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) { ArrayList<ArrayList<Integer>> results=new ArrayList<ArrayList<Integer>>(); if(num==null) return results; Arrays.sort(num); helper(num,0,target,results,new ArrayList<Integer>()); return results; } private void helper(int[] candidates,int start,int target, ArrayList<ArrayList<Integer>> results,ArrayList<Integer> temp){ if(target==0){ results.add(new ArrayList<Integer>(temp)); return; } for(int i=start;i<candidates.length;i++){ if(i>start&&candidates[i]==candidates[i-1]) continue; if(candidates[i]<=target){ temp.add(candidates[i]); helper(candidates,i+1,target-candidates[i],results,temp); temp.remove(temp.size()-1); } } } }
LeetCode Solutions : Combination Sum I & II
标签:leetcode java algorithms datastructure np
原文地址:http://blog.csdn.net/lviiii/article/details/39008797