Java easy to understand recursive solution.


  • 0
    C
    public List<List<Integer>> combinationSum2(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[] nums, int target, int idx, List<Integer> path, List<List<Integer>> ret) {
        if (target <= 0) {
            if (target == 0) {
                ret.add(path);
            }
            return; // backtracking
        }
        for (int i = idx; i < nums.length; i++) {
            if (i > idx && nums[i] == nums[i-1]) {
                continue;
            }
            List<Integer> p = new ArrayList<>(path);
            p.add(nums[i]);
            dfs(nums, target-nums[i], i+1, p, ret);
        }
    }

Log in to reply
 

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