40. Combination Sum II (not use before so int I = start, dfs(i+1), and sort

time: O(2^n), candidate choose or not choose, n times

space: O(target)

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates);
        dfs(result, candidates, target, new ArrayList<>(), 0);
        return result;
    }
    private void dfs(List<List<Integer>> result, int[] nums, int target, List<Integer> list, int start) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = start; i < nums.length; i++) {
            if (i > start && nums[i] == nums[i-1]) {
                continue;
            }
            list.add(nums[i]);
            dfs(result, nums, target - nums[i], list, i+1);
            list.remove(list.size()-1);
        }
    }
}

latest one

Last updated

Was this helpful?