代码随想录算法训练营第27天第七章 回溯算法part03● 39. 组合总和● 40.组合总和II● 131.分割回文串

39. 组合总和

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // 储存所有满足条件的组合
        List<List<Integer>> result = new ArrayList<>();

        // 储存当前组合

        List<Integer> combination = new ArrayList<>();


        backtrack(candidates, target, result, combination, 0);

        return result;
    }

    // 回溯法

    private void backtrack(int[] candidates, int target, List<List<Integer>> result, List<Integer> combination, int start){
        // 如果目标值为 0, 说明当前组合满足条件 将其添加到结果列表中
        if(target == 0){
            result.add(new ArrayList<>(combination));
            return;
        }

        //遍历候选数组, 从start 索引开始

        for(int i = start; i< candidates.length; i++){
            int num = candidates[i];
            // 如果当前数字小于等于目标值, 则可以将其加入到当前组合
            if(num <= target){
                combination.add(num);
                //继续回溯,此时目标值减去当前数字,下一轮搜索仍从当前索引开始,因为可以重复使用当前数字

                backtrack(candidates, target - num, result, combination, i);
                //回溯完成后,移除最后一个元素,尝试其他数字

                combination.remove(combination.size() - 1);
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值