Combination Sum, Leetcode 解题笔记

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

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 2,3,6,7 and target 7,
A solution set is:
[2, 2, 3]

典型的DFS递归题,一个注意的知识点是Java对于所有的object都是pass by reference,但是Java对method的arguments是pass by value的。
Java does manipulate objects by reference, and all object variables are references. However, Java doesn’t pass method arguments by reference; it passes them by value.


为什么要搞清这个概念呢?注意在下面的code中第11行,ret.add(new ArrayList(sol));这里要add的应该是一个复制的全新list,而不能直接把sol这个list加到结果ret里面去。因为后面我们会不断的修改sol,如果直接加sol这个list,最终ret里面已经被加进去的list其实全都是sol这一个list,最后的结果会返回一个空list。

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> sol = new ArrayList<Integer>();
        search(ret, sol, candidates, target, 0, 0);
        return ret;
    public void search(ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> sol, int[] candidates, int target, int start, int sum){
        if(sum == target){
            ret.add(new ArrayList<Integer>(sol));
        if(sum > target){
            while(start < candidates.length && sum+candidates[start] <= target){
                search(ret, sol, candidates, target, start, sum+candidates[start]);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s