Friday, November 20, 2015

[leetcode] Combination Sum

debug了半天发现原来把index 当成i
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (target <= 0 || candidates == null) return result;
        Arrays.sort(candidates);
        ArrayList<Integer> temp = new ArrayList<Integer>();
        recur(candidates, 0, new ArrayList<Integer>(), target);
        return result;
    }

    private void recur(int []candidates, int index, List<Integer> fromPrev, int target){
        if (index == candidates.length || target < 0) return;
        if (target == 0){
            List<Integer> temp = new ArrayList<Integer>(fromPrev);
            result.add(temp);
            return;
        }
        for (int i = index; i < candidates.length; i++){
            if (i < candidates.length-1 && candidates[i] == candidates[i+1]) i++;
            fromPrev.add(candidates[i]);
            recur(candidates, i, fromPrev, target-candidates[i]);
            fromPrev.remove(fromPrev.size()-1);
        }
    }
}

No comments:

Post a Comment