https://leetcode.com/problems/combination-sum/
先对candidates进行排序,原因有两点,一是最后的结果中要求每个combo中的数字是排好序的;二是排好序会方便我们的递归调用,因为如果当前的candidate加到combo里面会让sum超过target,我们就没必要对后面的candidate进行考虑了。
然后就是典型的递归调用,注意两点,一是终止条件,二是递归的部分。
1 public class Solution { 2 public List<List<Integer>> combinationSum(int[] candidates, int target) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 5 // sort candidates 6 Arrays.sort(candidates); 7 8 // call helpFunc to find all the combinations 9 List<Integer> combo = new ArrayList<Integer>(); 10 helpFunc(res, combo, candidates, 0, target); 11 12 return res; 13 } 14 15 public void helpFunc(List<List<Integer>> res, List<Integer> combo, int[] candidates, int idx, int remain) { 16 // end condition 17 if (remain == 0) { 18 res.add(new ArrayList<Integer>(combo)); 19 return; 20 } 21 22 // recursive 23 for (int i = idx; i < candidates.length; i++) { 24 if (candidates[i] <= remain) { 25 combo.add(candidates[i]); 26 helpFunc(res, combo, candidates, i, remain-candidates[i]); 27 combo.remove(combo.size()-1); 28 } 29 else { 30 return; 31 } 32 } 33 } 34 }
Q1. 怎么知道Array和List的长度
A: a.length; l.size();
Q2. Java里面值传递还是指针传递
A:
Q3. 如何新建一个List<List<Integer>>
A: 正确的方式:List<List<Integer>> l = new ArrayList<List<Integer>>();
错误的方式:List<List<Integer>> l = new List<ArrayList<Integer>>();
原文:http://www.cnblogs.com/jaysha/p/5194864.html