LeetCode--回溯算法系列:持续更新

本文探讨了如何使用回溯算法解决两个经典问题:数组的所有子集(幂集)生成和无重复元素数组的目标数字组合。分别给出了Java实现的解决方案,详细解析了算法思路和代码实现,适用于理解回溯法在解决组合问题中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文持续更新回溯算法相关题目~~

题目1:

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
class Solution {
    List<List<Integer>> lists = new ArrayList<List<Integer>>();
    
    public List<List<Integer>> subsets(int[] nums) {
        backTrace(new ArrayList<Integer>(), 0, nums);
        return lists;
    }

    private void backTrace(List<Integer> list, int from, int[] nums){
        lists.add(new ArrayList(list));
        for(int i=from;i<nums.length;i++){
            list.add(nums[i]);
            backTrace(list, i+1, nums);
            list.remove((Object)nums[i]);
        }
    }
}

题目2:

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

candidates 中的数字可以无限制重复被选取。

输入:candidates = [2,3,6,7], target = 7,
所求解集为:[[7],[2,2,3]]
class Solution {
    List<List<Integer>> lists = new ArrayList<List<Integer>>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backTrace(new ArrayList<Integer>(), candidates, 0, target);
        return lists;
    }

    private void backTrace(List<Integer> list, int[] candidates, int total, int target){
        if(total>target){//上次加完后,已经大于target了
            return;
        }else if(total==target){
            List<Integer> willBeAdd = new ArrayList(list);
            Collections.sort(willBeAdd);
            if(!lists.contains(willBeAdd))
                lists.add(willBeAdd);
            return;
        }
        for(int i=0;i<candidates.length;i++){
            list.add(candidates[i]);
            backTrace(list, candidates, total+candidates[i], target);
            list.remove(list.size()-1);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的Coder*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值