Joey LIU | NANTSOU


 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
26
27
28
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (candidates == null || candidates.length == 0) {
            return res;
        }
        Arrays.sort(candidates);
        dfs(candidates, target, 0, 0, new ArrayList<Integer>(), res);
        return res;
    }
    
    private void dfs(int[] candidates, int target, int i, int sum, List<Integer> tmp, List<List<Integer>> res) {
        if (sum == target) {
            res.add(new ArrayList<>(tmp));
            return;
        }
        
        for (; i < candidates.length; i++) {
            if (sum + candidates[i] > target) {
                break;
            }
            tmp.add(candidates[i]);
            dfs(candidates, target, i, sum + candidates[i], tmp, res);
            tmp.remove(tmp.size() - 1);
        }
        
    }
}