【Hot100】LeetCode—39. 组合总和



1- 思路

注意如果借助 startIndex 实现,理解 startIndex 的含义

  • 在本题目中,由于同一个元素可以重复选取,因此 startIndex 在传递的过程中,不需要进行 +1 操作,传递的值为i

2- 实现

⭐39. 组合总和——题解思路

在这里插入图片描述

class Solution {

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backTracing(candidates, target, 0, 0);
        return res;
    }

    // 1. 回溯参数及返回值
    public void backTracing(int[] candidates, int target, int nowSum, int startIndex) {

        if (nowSum > target) {
            return;
        }

        // 2. 结束条件
        if (nowSum == target) {
            res.add(new ArrayList(path));
            return;
        }

        // 回溯
        for (int i = startIndex; i < candidates.length; i++) {
            nowSum += candidates[i];
            path.add(candidates[i]);
            backTracing(candidates, target, nowSum, i);
            nowSum -= candidates[i];
            path.remove(path.size() - 1);
        }
    }
}

3- ACM 实现

public class combination {


    static List<List<Integer>> res = new ArrayList<>();
    static List<Integer> path = new ArrayList<>();
    public static List<List<Integer>> combine(int[] candidates,int target){
        // 回溯
        backTracing(candidates,target,0,0);
        return res;
    }

    public static void backTracing(int[] candidates,int target,int nowSum,int startIndex){

        // 终止条件
        if(nowSum>target){
            return;
        }
        if(nowSum==target){
            res.add(new ArrayList<>(path));
        }

        //回溯
        for(int i = startIndex;i<candidates.length;i++){
            nowSum += candidates[i];
            path.add(candidates[i]);
            backTracing(candidates,target,nowSum,i);
            nowSum -= candidates[i];
            path.remove(path.size()-1);
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        input = input.replace("[","").replace("]","");
        String[] parts = input.split(",");
        int[] nums = new int[parts.length];
        for(int i = 0 ; i < parts.length;i++){
            nums[i] = Integer.parseInt(parts[i]);
        }
        System.out.println("输入target");
        int target = sc.nextInt();
        System.out.println("结果是"+combine(nums,target).toString());

    }
}
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值