LeetCode 经典题:“组合总和”

一、题目描述

给定一个无重复元素的正整数数组 candidates 和一个正整数 target ,找出 candidates 中所有可以使数字和为目标数 target 的组合。candidates 中的数字可以无限制重复被选取。

示例

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

二、解题思路与多方法实现

方法一:回溯法

思路

回溯法是一种通过尝试所有可能的组合来找到解决方案的算法。对于本题,我们从数组 candidates 的第一个元素开始,尝试将其加入当前组合中,然后递归地继续尝试加入其他元素,直到当前组合的和等于 target 或者超过 target

  1. 递归函数设计
    • 函数参数包括当前的组合列表 combination,当前已经使用的和 currentSum,当前考虑的 candidates 数组的起始索引 startIndex
    • currentSum 等于 target 时,将当前组合 combination 加入结果列表 result 中。
    • currentSum 大于 target 时,直接返回,因为继续添加元素不会得到符合条件的组合。
    • 否则,从 startIndex 开始遍历 candidates 数组,将当前元素加入 combination,更新 currentSum,然后递归调用自身,startIndex 保持不变(因为数字可以无限制重复选取)。递归结束后,回溯,即从 combination 中移除最后一个元素,恢复到递归前的状态。
  2. 主函数
    • 初始化结果列表 result,调用递归函数,起始索引为 0,当前组合为空,当前和为 0
代码实现(Java)
import java.util.ArrayList;
import java.util.List;

public class CombinationSum {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> combination = new ArrayList<>();
        backtrack(candidates, target, 0, combination, 0, result);
        return result;
    }

    private void backtrack(int[] candidates, int target, int startIndex, List<Integer> combination, int currentSum, List<List<Integer>> result) {
        if (currentSum == target) {
            result.add(new ArrayList<>(combination));
            return;
        }
        if (currentSum > target) {
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            combination.add(candidates[i]);
            currentSum += candidates[i];
            backtrack(candidates, target, i, combination, currentSum, result);
            combination.remove(combination.size() - 1);
            currentSum -= candidates[i];
        }
    }
}
代码解释
  1. 主函数
    • 创建一个 List<List<Integer>> 类型的 result 用于存储所有符合条件的组合。
    • 创建一个 List<Integer> 类型的 combination 用于存储当前正在构建的组合。
    • 调用 backtrack 函数开始回溯过程。
  2. 回溯函数 backtrack
    • currentSum 等于 target 时,将当前的 combination 复制一份加入 result 中,因为 combination 会在后续回溯过程中被修改。
    • currentSum 大于 target 时,直接返回,不再继续尝试。
    • 遍历 candidates 数组,从 startIndex 开始,将当前元素加入 combination,更新 currentSum,递归调用 backtrackstartIndex 保持为 i,以便重复选取当前元素。
    • 递归结束后,移除 combination 中最后一个元素,同时减去对应的和,回溯到上一步状态。

方法二:动态规划法

思路

动态规划的核心是通过求解子问题来解决原问题。我们定义一个 List<List<Integer>> 类型的数组 dp,其中 dp[i] 表示和为 i 的所有组合。

  1. 初始化
    • dp[0] 是一个空列表,因为和为 0 的组合是空组合。
    • 对于其他 dp[i],初始化为空列表。
  2. 状态转移
    • 遍历 candidates 数组中的每个元素 num
    • 对于每个 num,从 numtarget 遍历所有的和 j
    • 如果 dp[j - num] 不为空,说明存在和为 j - num 的组合,将 num 添加到这些组合中,就得到了和为 j 的新组合,并将这些新组合加入 dp[j]
代码实现(Java)
import java.util.ArrayList;
import java.util.List;

public class CombinationSumDP {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>>[] dp = new List[target + 1];
        for (int i = 0; i <= target; i++) {
            dp[i] = new ArrayList<>();
        }
        dp[0].add(0);

        for (int num : candidates) {
            for (int j = num; j <= target; j++) {
                if (dp[j - num].size() > 0) {
                    for (int combination : dp[j - num]) {
                        List<Integer> newCombination = new ArrayList<>(dp[j - num].get(combination));
                        newCombination.add(num);
                        dp[j].add(newCombination);
                    }
                }
            }
        }
        return dp[target];
    }
}
代码解释
  1. 初始化 dp 数组:创建一个长度为 target + 1List<List<Integer>> 数组 dp,并将每个位置初始化为一个空的 ArrayList。将 dp[0] 加入一个虚拟元素 0(仅用于标记和为 0 的情况)。
  2. 双重循环进行状态转移
    • 外层循环遍历 candidates 数组中的每个元素 num
    • 内层循环从 numtarget 遍历所有的和 j
    • 如果 dp[j - num] 不为空,说明存在和为 j - num 的组合。遍历这些组合,将 num 添加到每个组合中,形成新的和为 j 的组合,并将新组合加入 dp[j]
  3. 返回结果:最后返回 dp[target],即和为 target 的所有组合。

三、复杂度分析

时间复杂度

  • 回溯法:在最坏情况下,时间复杂度为指数级,因为可能会尝试所有可能的组合。具体来说,时间复杂度为 O(2n)O(2^n)O(2n),其中 ncandidates 数组的长度。但在实际运行中,由于剪枝操作(当 currentSum > target 时返回),性能会优于指数级。
  • 动态规划法:时间复杂度为 O(m×target)O(m \times target)O(m×target),其中 mcandidates 数组的长度。因为我们有两层循环,外层循环遍历 m 次,内层循环遍历 target 次。

空间复杂度

  • 回溯法:空间复杂度主要取决于递归调用栈的深度和存储结果的空间。在最坏情况下,递归深度为 target,所以空间复杂度为 O(target)O(target)O(target)。存储结果的空间取决于符合条件的组合数量,在最坏情况下可能也是指数级的,但通常会小于递归栈空间。
  • 动态规划法:空间复杂度为 O(target×k)O(target \times k)O(target×k),其中 k 是平均每个 dp[i] 中组合的数量。因为 dp 数组的长度为 target + 1,每个位置存储的组合列表长度平均为 k

四、总结

“组合总和”这道中等难度的题目通过回溯法和动态规划法展示了两种不同的解题思路。回溯法直观且容易理解,通过深度优先搜索尝试所有可能的组合,并利用剪枝操作优化性能。动态规划法则通过求解子问题,以空间换时间的方式,高效地构建出所有符合条件的组合。在实际应用中,如果 candidates 数组长度较短且 target 较大,回溯法可能更合适;如果 candidates 数组长度较长且 target 相对较小,动态规划法可能在性能上更优。希望通过对这两种方法的详细分析,能帮助大家更好地理解和解决类似的组合问题,提升算法设计和分析能力。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值