40. Combination Sum II

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        if (candidates == null || candidates.length == 0) return ans;

        Arrays.sort(candidates);
        dfs(candidates, 0, 0, target, new ArrayList<Integer>(), ans);


        return ans;
    }

    private void dfs(int[] candidates, int index, int sum, int target, List<Integer> path, List<List<Integer>> ans){
        if (sum >= target){
            if (sum == target){
                ans.add(new ArrayList<>(path));    
            }
            return;
        }

        for (int i = index; i < candidates.length; i++){
            if (i > index && candidates[i] == candidates[i - 1]) continue;

            sum += candidates[i];
            path.add(candidates[i]);
            dfs(candidates, i + 1, sum, target, path, ans);
            sum -= candidates[i];
            path.remove(path.size() - 1);
        }
    }
}

results for ""

    No results matching ""