Java easy to understand recursive solution.


  • 0
    C
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> ret = new ArrayList<>();
        dfs(candidates, target, 0, new ArrayList<>(), ret);
        return ret;
    }
    
    private void dfs(int[] candidates, int target, int idx, List<Integer> path, List<List<Integer>> ret) {
        if (target <= 0) {
            if (target == 0) {
                ret.add(path);
            }
            return;
        }    
        for (int i = idx; i < candidates.length; i++) {
            List<Integer> p = new ArrayList<>(path);
            p.add(candidates[i]);
            dfs(candidates, target-candidates[i], i, p, ret);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.