力扣39. 组合总和

Problem: 39. 组合总和

题目描述

在这里插入图片描述在这里插入图片描述

思路及解题方法

1.创建一个 res 变量存储所有满足条件的组合结果,使用 track 变量记录当前的组合路径,使用 trackSum 变量记录当前路径中元素的和。

2.回溯方法 backtrack:

2.1.基本情况1:如果 trackSum 等于目标 target,则将当前路径 track 添加到结果 res 中,并返回。
2.2.基本情况2:如果 trackSum 大于目标 target,则直接返回。

3.循环与选择:

3.1.循环从 start 位置开始遍历 nums 数组。
3.2.将当前元素添加到 track 中,并更新 trackSum。
3.3.递归调用 backtrack 方法,并将 start 位置保持为 i,允许重复选择当前元素。
3.4.回溯:从 track 中移除最后一个元素,并更新 trackSum,以便尝试其他组合。

复杂度

时间复杂度:

O ( 2 N ) O(2^N) O(2N);其中 N N N为数组candidates的长度

空间复杂度:

O ( N × 2 N ) O(N \times 2^N) O(N×2N)

Code

class Solution {
    List<List<Integer>> res = new LinkedList<>();
    // Record the backtracking path
    LinkedList<Integer> track = new LinkedList<>();
    // Record the path sum in track
    int trackSum = 0;

    /**
     * Combination Sum
     *
     * @param candidates Given array
     * @param target     Given number
     * @return List<List < Integer>>
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates.length == 0) {
            return res;
        }
        backtrack(candidates, 0, target);
        return res;
    }

    /**
     * Backtracking functions implement functions
     *
     * @param nums   Given array
     * @param start  Decision stage
     * @param target Given number
     */
    private void backtrack(int[] nums, int start, int target) {
        // base case, find the target and record the result
        if (trackSum == target) {
            res.add(new LinkedList<>(track));
            return;
        }
        // base case, exceed the target sum, stop the downward traversal
        if (trackSum > target) {
            return;
        }
        for (int i = start; i < nums.length; ++i) {
            trackSum += nums[i];
            track.add(nums[i]);
            backtrack(nums, i, target);
            trackSum -= nums[i];
            track.removeLast();
        }
    }
}
  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值