栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode:39. 组合总和

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode:39. 组合总和

问题描述(原题链接)

  给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。
  你可以按 任意顺序 返回这些组合。candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 对于给定的输入,保证和为 target 的不同组合数少于 150 个。

代码:
class Solution {
    public List> combinationSum(int[] candidates, int target) {
        //回溯法
        List>res = new ArrayList>();
        List temp = new ArrayList();
        search(candidates,target,res,temp,0);
        return res;
    }
    public void search(int[] candidates,int target,List> res,List temp,int num){
        if(num==candidates.length)
        return;
        if(target==0){
            res.add(new ArrayList(temp));
            return;
        }
        if(target-candidates[num]>=0){ //选择当前数
            temp.add(candidates[num]);
            search(candidates,target-candidates[num],res,temp,num);  //可以无限选,所以num不加1
            temp.remove(temp.size()-1);
        }
        search(candidates,target,res,temp,num+1);
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/832051.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号