【LeetCode】组合总和II

题目

上一题的差别在于每个数字只能被使用一次,因此需要考虑去重的问题。而测试用例又对时间要求比较严格,所以需要用比较高效的去重方法。

描述

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次
注意:解集不能包含重复的组合。

链接:

https://leetcode.cn/problems/combination-sum-ii/description/

这道题的解法是参考官方题解写出的。

思路

  1. 使用试探-回溯法对答案进行搜索
  2. 预先收集每个candidate的数量,在回溯的时候统一处理
  3. 对于已经超出总和的情况做剪枝

复杂度

  • 时间复杂度: O(2^n∗n)
  • 空间复杂度: O(n)

代码

function combinationSum2(candidates: number[], target: number): number[][] {
    candidates.sort((a, b) => a - b);
    const result: number[][] = [];
    const res: number[] = [];
    const countMap = new Map<number, number>();

    // 收集个数
    const collectCount = () => {
        for (const c of candidates) {
            if (!countMap.has(c)) {
                countMap.set(c, 1);
            } else {
                countMap.set(c, countMap.get(c) + 1);
            }
        }
    }
    collectCount();
    const mapArray = [...countMap.keys()];
    
    const backtrack = (left: number, index: number) => {
        if (left === 0) {
            result.push([...res]);
            return;
        }
        const n = mapArray[index];
        if (index === mapArray.length || left < n) return;
        const count = countMap.get(n);

        // 不选这个数
        backtrack(left, index + 1);

        const most = Math.min(count, Math.floor(left / n));
        // 选1到most次这个数
        for (let i = 1; i <= most; i++) {
            res.push(n);
            backtrack(left - i * n, index + 1);
        }
        // 逐次恢复
        for (let i = 0; i < most; i++) {
            res.pop();
        }
    }
    backtrack(target, 0);
    
    return result;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值