首页 > 其他 > 详细

Leetcode - Combination Sum

时间:2016-02-17 21:00:35      阅读:184      评论:0      收藏:0      [点我收藏+]
  • 题目链接

   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 }
View Code

 

  • 知识欠缺

  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>>();

 

  • 更好的代码

 

Leetcode - Combination Sum

原文:http://www.cnblogs.com/jaysha/p/5194864.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!