Blage's Coding Blage's Coding
Home
算法
  • 手写Spring
  • SSM
  • SpringBoot
  • JavaWeb
  • JAVA基础
  • 容器
  • Netty

    • IO模型
    • Netty初级
    • Netty原理
  • JVM
  • JUC
  • Redis基础
  • 源码分析
  • 实战应用
  • 单机缓存
  • MySQL

    • 基础部分
    • 实战与处理方案
    • 面试
  • ORM框架

    • Mybatis
    • Mybatis_Plus
  • SpringCloudAlibaba
  • MQ消息队列
  • Nginx
  • Elasticsearch
  • Gateway
  • Xxl-job
  • Feign
  • Eureka
  • 面试
  • 工具
  • 项目
  • 关于
🌏本站
🧸GitHub (opens new window)
Home
算法
  • 手写Spring
  • SSM
  • SpringBoot
  • JavaWeb
  • JAVA基础
  • 容器
  • Netty

    • IO模型
    • Netty初级
    • Netty原理
  • JVM
  • JUC
  • Redis基础
  • 源码分析
  • 实战应用
  • 单机缓存
  • MySQL

    • 基础部分
    • 实战与处理方案
    • 面试
  • ORM框架

    • Mybatis
    • Mybatis_Plus
  • SpringCloudAlibaba
  • MQ消息队列
  • Nginx
  • Elasticsearch
  • Gateway
  • Xxl-job
  • Feign
  • Eureka
  • 面试
  • 工具
  • 项目
  • 关于
🌏本站
🧸GitHub (opens new window)
  • 数组

  • 链表

  • 字符串

  • 二叉树

  • 动态规划

  • 深搜回溯

    • 46.全排列
    • 93.复原IP地址
    • 1079.活字印刷
    • 6441. 求一个整数的惩罚数
    • 47. 全排列 II
    • 78. 子集
    • 79. 单词搜索
    • 207. 课程表
    • 399. 除法求值
    • 22. 括号生成
    • 39. 组合总和
    • 2746. 字符串连接删减字母
    • 931. 下降路径最小和
    • 40. 组合总和 II
      • 1.回溯+减枝
    • 332. 重新安排行程
    • 51. N 皇后
    • 37. 解数独
    • 2050. 并行课程 III
    • 841. 钥匙和房间
    • 2850. 将石头分散到网格图的最少移动次数
    • 2316. 统计无向图中无法互相到达点对数
    • 剑指offer12
    • 剑指offer38
  • 数学贪心

  • 堆栈队列

  • 前缀和

  • 算法设计

  • 位运算

  • WA

  • 算法
  • 深搜回溯
phan
2023-07-17
目录

40. 组合总和 II

# 40. 组合总和 II (opens new window)

# 1.回溯+减枝

难点在于剪枝,考虑如下用例如何进行优化:candidates=[1,1,1,1,3],target=4

剪枝算法有两个关键点:

  • 每一层不需要选择重复数字
  • 要保证数组中重复数字能够被多次选中

也就说重复数字可以跨层重复选,不能同层重复选。实现时如果当前这层直接过滤重复答案,但是这样一来重复数字在第二层第三层也选不了(违背上面第二条)。因此在剪枝判断加了一层 i>index 判断条件,也就说当前这层无论如何先把第一个index的值选了,再进行同层之间的去重。

class Solution {
    List<List<Integer>> res=new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        dfs(new ArrayList<Integer>(),candidates,target,0,0);
        return res;
    }
    public void dfs(List<Integer> path,int[] candidates,int target,int sum,int index){
        if(target==sum){
            res.add(new ArrayList<>(path));
            return ;
        }
        for(int i=index;i<candidates.length;i++){
            if(sum+candidates[i]>target) return;
			//剪枝
            if(i>index&&candidates[i]==candidates[i-1]){
                while(i<candidates.length&&candidates[i-1]==candidates[i])i++;
                if(i==candidates.length)return ;
            }
            path.add(candidates[i]);
            dfs(path,candidates,target,sum+candidates[i],i+1);
            path.remove(path.size()-1);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
编辑 (opens new window)
#Leetcode#回溯
上次更新: 2023/12/15, 15:49:57
931. 下降路径最小和
332. 重新安排行程

← 931. 下降路径最小和 332. 重新安排行程→

Theme by Vdoing | Copyright © 2023-2024 blageCoder
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式