LeetCode 40. 组合总和 II

40. 组合总和 II

【回溯 + 去重】先对元素排序,如果当前元素和前一个元素重复nums[i] == nums[i - 1],并且前一个元素nums[i - 1]没有被用过 !st[i - 1],那就说明前面那个元素是回溯回来的,这时候如果再选用重复的元素 nums[i]就会重复,所以遇到这种情况需要跳过。

class Solution {

    List<List<Integer>> ans = new ArrayList();
    LinkedList<Integer> list = new LinkedList();
    Set<Integer> st = new HashSet();
    int[] nums;
    int n, target;

    void dfs(int t, int sum) {
        if (t == n) {
            if (sum == target) ans.add(new ArrayList(list));
            return;
        }
        dfs(t + 1, sum);
        if (t > 0 && !st.contains(t - 1) && nums[t] == nums[t - 1]) return;
        if (sum + nums[t] > target) return;
        list.add(nums[t]);
        st.add(t);
        dfs(t + 1, sum + nums[t]);
        list.pollLast();
        st.remove(t);
    }

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        this.nums = candidates;
        this.n = this.nums.length;
        this.target = target;
        dfs(0, 0);
        return ans;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值