【力扣】39. 组合总和

84 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第 5 天,点击查看活动详情

题目链接

39. 组合总和 - 力扣(LeetCode)

题目描述

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

测试用例

用例1:

输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

限制

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 200
  • candidate 中的每个元素都 互不相同
  • 1 <= target <= 500

题目分析

这种题与 用硬币去兑换零钱的题型 类似,都是需要我们使用给定的数组中的元素,去拼接组合得到目标数。本题特殊一点的地方在于,“硬币” 的数量是无限的,并且,还需要我们给出可以得到 target 的全部组合

在这里,我们可以借鉴动态规划里的 DP打表 法,通过一个数组 result 去记录下,对应下标 index ,通过 candidates 提供的元素,有多少种组合方式来得 index ,用一个二维数组 arrs 去记录下这些组合的方式,并记录下来: result[index] = arrs

通过遍历 candidates 中的元素,我们可以得到一个转移方程: f(n) = f(m) + candidates[i]

通过示例来演示上述的思路:

f(1) = []
f(2) = [[2]]
f(3) = [[3]]
f(4) = f(2) + 2 = [[2,2]]
f(5) = f(2) + 3 = f(3) + 2 = [[2,3]]
f(6) = f(4) + 2 = f(3) + 3 = [[2,2,3],[3,3,3]]
...

我们从 f(1) 开始,一步步的记录下每一个下标对应的组合方案,供后面 DP表 使用

在上述的遍历过程中,需要注意 f(5) 有两种组合 f(2)+3f(3)+2,组合是不同的,但最后得到的结果仅仅是元素的顺序不同,实际上表示的都是 [2,3] 这一种组合,我们在处理的时候,需要注意并去除重复项

代码实现

完整的代码实现如下

var combinationSum = function (candidates, target) {
        candidates.sort((a, b) => a - b);
        let arr = new Array(target + 1);
        for (let i = 0; i < arr.length; i++) {
            arr[i] = [];
            for (let j = 0; candidates[j] <= i; j++) {
                if (i == candidates[j]) {
                    arr[i].push([i]);
                } else {
                    for (let k = 0; k < arr[i - candidates[j]].length; k++) {
                        let temp = arr[i - candidates[j]][k].slice(0);
                        temp.push(candidates[j])
                        arr[i].push(temp);
                    }
                }
            }
            arr[i] = rmRepeat(arr[i]);
        }
        function rmRepeat(arrs) {
            return [...new Set(arrs.map(arr => arr.sort().join(',')))].map(n => n.split(','));
        }
        return arr.pop();
    };

image.png

此种解法性能不怎么样,但胜在便于理解