leetcode39 组合总和

leetcode39 组合总和

image-20241129112802700

思路:

这题也是用回溯,但是考虑到不能重复,所以用一个currentNum记录当前遍历到哪了,按照大小顺序遍历防止重复就行。

class Solution {
    //11:10-11:18
    public void dfs(int[] candidates,List<List<Integer>> ans,int currentNum,List<Integer> list,int sum,int target){
        if (sum==target){
            ans.add(new ArrayList<>(list));
        }
        if(sum>target){
            return;
        }
        if (currentNum>candidates.length){
            return;
        }
        for (int i = currentNum; i < candidates.length; i++) {
            int num=candidates[i];
            list.add(num);
            dfs(candidates,ans,i,list,sum+num,target);
            list.remove(list.size()-1);
        }
    }
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans=new ArrayList<>();
        dfs(candidates,ans,0,new ArrayList<>(),0,target);
        return ans;
    }
}

如果不用currentNum的话,就是遍历所有的组合了(带顺序的)。

class Solution {
    //11:10-11:18
    public void dfs(int[] candidates,List<List<Integer>> ans,List<Integer> list,int sum,int target){
        if (sum==target){
            ans.add(new ArrayList<>(list));
        }
        if(sum>target){
            return;
        }
        for (int i = 0; i < candidates.length; i++) {
            int num=candidates[i];
            list.add(num);
            dfs(candidates,ans,list,sum+num,target);
            list.remove(list.size()-1);
        }
    }
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans=new ArrayList<>();
        dfs(candidates,ans,new ArrayList<>(),0,target);
        return ans;
    }
}

image-20241129113020147

posted @   vast_joy  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示