首页 > 其他分享 >39. 组合总和 40.组合总和II 131.分割回文串

39. 组合总和 40.组合总和II 131.分割回文串

时间:2023-04-04 21:36:31浏览次数:36  
标签:39 target 组合 int res list candidates new 总和


39. 组合总和

39. 组合总和 40.组合总和II 131.分割回文串_leetcode


自己写的回溯算法:

class Solution {
    List<List<Integer>> list;
    LinkedList<Integer> res;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        list = new ArrayList<>();
        res = new LinkedList<>();
        f(candidates,target,0);
        return list;
    }
    void f(int[] candidates,int target,int idx){
        if(target == 0){
            list.add(new ArrayList(res));
            return;
        }
        for(int i = idx;i < candidates.length;i++){
            if(target < 0) break;
            res.add(candidates[i]);
            f(candidates,target - candidates[i],i);
            res.removeLast();
        }
    }
}

39. 组合总和 40.组合总和II 131.分割回文串_算法_02


优化,剪枝操作:

class Solution {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
       List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates); // 先进行排序
        backtracking(res, new ArrayList<>(), candidates, target, 0, 0);
        return res;
    }

    public void backtracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int idx) {
        // 找到了数字和为 target 的组合
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = idx; i < candidates.length; i++) {
            // 如果 sum + candidates[i] > target 就终止遍历
            if (sum + candidates[i] > target) break;
            path.add(candidates[i]);
            backtracking(res, path, candidates, target, sum + candidates[i], i);
            path.remove(path.size() - 1); // 回溯,移除路径 path 最后一个元素
        }
    }
}

39. 组合总和 40.组合总和II 131.分割回文串_java_03

40.组合总和II

39. 组合总和 40.组合总和II 131.分割回文串_java_04


去重关键:

if(i > idx && candidates[i] == candidates[i-1]) continue;

39. 组合总和 40.组合总和II 131.分割回文串_算法_05

class Solution {
    List<List<Integer>> list;
    List<Integer> res;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        list = new ArrayList<>();
        res = new ArrayList<>();
        Arrays.sort(candidates);
        f(candidates,target,0,0);
        return list;
    }
    void f(int[] candidates,int target,int sum,int idx){
        if(sum == target){
            list.add(new ArrayList(res));
            return;
        }
        for(int i = idx;i < candidates.length;i++){
        //这行代码去重关键,因为candidates是有序的
            if(i > idx && candidates[i] == candidates[i-1]) continue;
            if(sum + candidates[i] > target) break;
            res.add(candidates[i]);
            f(candidates,target,sum + candidates[i],i + 1);
            res.remove(res.size() - 1);
        }
    }
}

39. 组合总和 40.组合总和II 131.分割回文串_List_06


用标识判断:

如果candidates[i] == candidates[i - 1] 并且 used[i - 1] == false,就说明:前一个树枝,使用了candidates[i - 1],也就是说同一树层使用过candidates[i - 1]。

此时for循环里就应该做continue的操作。

class Solution {
    List<List<Integer>> list;
    List<Integer> res;
    boolean[] used;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        used = new boolean[candidates.length];
        list = new ArrayList<>();
        res = new ArrayList<>();
        Arrays.sort(candidates);
        f(candidates,target,0,0);
        return list;
    }
    void f(int[] candidates,int target,int sum,int idx){
        if(sum == target){
            list.add(new ArrayList(res));
            return;
        }
        for(int i = idx;i < candidates.length;i++){
            if(sum + candidates[i] > target) break;
            //判断是否是同一层
            if(i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) continue;
            used[i] = true;
            res.add(candidates[i]);
            f(candidates,target,sum + candidates[i],i + 1);
            used[i] = false;
            res.remove(res.size() - 1);
        }
    }
}

39. 组合总和 40.组合总和II 131.分割回文串_算法_07

131.分割回文串

39. 组合总和 40.组合总和II 131.分割回文串_java_08


回溯法:

39. 组合总和 40.组合总和II 131.分割回文串_sed_09

class Solution {
    List<List<String>> list;
    LinkedList<String> res;
    public List<List<String>> partition(String s) {
        list = new ArrayList<>();
        res = new LinkedList<>();
        f(s,0);
        return list;
    }
    void f(String s,int startIndex){
        if(startIndex == s.length()){
            list.add(new ArrayList(res));
            return;
        }
        for(int i = startIndex;i < s.length();i++){
            if(isP(s,startIndex,i)){
                res.add(s.substring(startIndex,i+1));
            }else{
                continue;
            }
            f(s,i+1);
            res.removeLast();
        }
    }
    boolean isP(String s,int startIndex,int end){
        for(int i = startIndex,j = end;i <= j;i++,j--){
            if(s.charAt(i) == s.charAt(j)){
                continue;
            }else{
                return false;
            }
        }
        return true;
    }
}

39. 组合总和 40.组合总和II 131.分割回文串_算法_10


标签:39,target,组合,int,res,list,candidates,new,总和
From: https://blog.51cto.com/u_15911055/6169669

相关文章

  • 216.组合总和III 17.电话号码的字母组合
    216.组合总和III回溯的常规思路做这道题:classSolution{List<List<Integer>>list=newArrayList<>();LinkedList<Integer>res=newLinkedList<>();publicList<List<Integer>>combinationSum3(intk,intn){f......
  • 解决适用EntityFramework生成时报错“无法解析依赖项。"EntityFramework 6.4.4" 与 '
    起因:通过vs2022创建mvc项目时,执行添加“包含视图的MVC5控制器(使用EntityFramework)时   点击添加,出现错误提示   解决方法:在您的解决方案资源管理器中,右键单击引用,管理nuget包,转到“已安装”选项卡并从EntityFramework.zh-Hans,卸载您的语言包,然后在重新添加......
  • cramfs-1.1/mkcramfs.c:446: undefined reference to `minor'
    在编译cramfs-1.1时报如下错误:/usr/bin/ld:/tmp/ccMb5KDC.o:infunction`print_node':/root/cramfs-1.1/mkcramfs.c:446:undefinedreferenceto`minor'/usr/bin/ld:/root/cramfs-1.1/mkcramfs.c:446:undefinedreferenceto`major'collect2:error:ldr......
  • mysql 插入解决时间报错 Incorrect datetime value:''
    1.打开MySQL命令行,检查当前数据库的严格模式:SELECT@@GLOBAL.sql_mode; 2.更新全局sql_mode参数:SETGLOBALsql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';3.检查是否更新成功:SELECT@@GLO......
  • 解决:Failed to start bean 'documentationPluginsBootstrapper'
    原因:在springboot2.6.0以后将SpringMVC默认路径匹配策略从AntPathMatcher更改为PathPatternParser,导致出错,解决办法是切换会原先的AntPathMatcher。解决:配置文件中加上spring:mvc:pathmatch:matching-strategy:ant_path_matcher ......
  • npm报错 npm ERR! Unexpected token '.'
    报错如下图:  报错原因:node版本太高解决办法:卸载node重新安装,或者使用nvm切换版本 mvm安装使用教程:https://www.cnblogs.com/tianxinya/p/17286467.html......
  • Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
    网上一堆说的,启动类的加@MapperScan,mybatis指定mapper路径,甚至说实体类与数据库连不上等等。都不行,后来比对下与另一个能正常启动的pom文件比对,发现是依赖没加入,包括connector依赖都没有。综上,思路是未连接数据库的原因。......
  • [Leetcode Weekly Contest]339
    链接:LeetCode[Leetcode]2609.最长平衡子字符串给你一个仅由0和1组成的二进制字符串s。如果子字符串中所有的0都在1之前且其中0的数量等于1的数量,则认为s的这个子字符串是平衡子字符串。请注意,空子字符串也视作平衡子字符串。返回s中最长的平衡子字符串......
  • Problem B. Harvest of Apples 组合数求和(莫队没怎么看懂)
    ProblemB.HarvestofApplesTimeLimit:4000/2000MS(Java/Others)    MemoryLimit:262144/262144K(Java/Others)TotalSubmission(s):3775    AcceptedSubmission(s):1450 ProblemDescriptionTherearenapplesonatree,numberedfrom1ton.Count......
  • 洛谷 P2398. GCD SUM
    题目描述求$$\sum\limits_{i=1}^n\sum\limits_{j=1}^n\gcd(i,j)$$输入:2输出:5算法1 线性筛 $O(n)$将式子变形:要知道一个前置定理$\sum\limits_{d|n}\varphi(d)=n$艾弗森约定:定义$\\\[P]$=$$\begin{cases}P\text{}is\text{}tr......