当前位置: 首页 > news >正文

组合总和(combination-sum)

题目

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

代码

package combination_sum;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class Solution {

    private List<List<Integer>> res = new ArrayList<>();
    private int[] candidates;
    private int len;

    /**递归 深度优先dfs 回溯*/
    private void findCombinationSum(int residue, int start, Stack<Integer> pre) {
        if (residue == 0) {
            // Java 中可变对象是引用传递,因此需要将当前 path 里的值拷贝出来
            res.add(new ArrayList<Integer>(pre));
            return;
        }
        // 优化添加的代码2:在循环的时候做判断,尽量避免系统栈的深度
        // residue - candidates[i] 表示下一轮的剩余,如果下一轮的剩余都小于 0 ,就没有必要进行后面的循环了
        // 这一点基于原始数组是排序数组的前提,因为如果计算后面的剩余,只会越来越小
        for (int i = start; i < len && residue - candidates[i] >= 0; i++) {
            pre.add(candidates[i]);
            // 【关键】因为元素可以重复使用,这里递归传递下去的是 i 而不是 i + 1
            findCombinationSum(residue - candidates[i], i, pre);
            pre.pop();
        }
    }

    /**组合总和  (combination-sum) */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        int len = candidates.length;
        if (len == 0) {
            return res;
        }
        // 优化添加的代码1:先对数组排序,可以提前终止判断
        Arrays.sort(candidates);
        this.len = len;
        this.candidates = candidates;
        findCombinationSum(target, 0, new Stack<Integer>());
        return res;
    }

    public static void main(String[] args) {
        int[] candidates = {2, 3, 6, 7};
        int target = 7;
        Solution solution = new Solution();
        List<List<Integer>> combinationSum = solution.combinationSum(candidates, target);
        System.out.println(combinationSum);
    }
}

相关文章:

  • 组合总和combination-sum
  • 如何查看隐藏的密码(限chrome浏览器)
  • 最大子序和(maximum-subarray)——动态规划和贪心双解法
  • Deepin系统安装SSH服务
  • Deepin Gif转mp4
  • 零钱兑换(coin-change) 动态规划问题
  • 批量识别图版中的文字信息之百度AI文字识别
  • 操作系统 术语表
  • GoldenDict 调用百度翻译(多段文本)
  • Hexo常用命令
  • 最小路径和(minimum-path-sum)
  • Leetcode.4.寻找两个有序数组的中位数(problems/median-of-two-sorted-arrays)
  • python调试PDB工具命令
  • PAT乙级介绍
  • PAT乙级1011. A+B和C(C语言)
  • extjs4学习之配置
  • gcc介绍及安装
  • JavaScript 一些 DOM 的知识点
  • Java的Interrupt与线程中断
  • mockjs让前端开发独立于后端
  • Python3爬取英雄联盟英雄皮肤大图
  • Web Storage相关
  • 程序员该如何有效的找工作?
  • 给自己的博客网站加上酷炫的初音未来音乐游戏?
  • 简单数学运算程序(不定期更新)
  • 将 Measurements 和 Units 应用到物理学
  • 力扣(LeetCode)357
  • 容器服务kubernetes弹性伸缩高级用法
  • 使用Maven插件构建SpringBoot项目,生成Docker镜像push到DockerHub上
  • 想写好前端,先练好内功
  • 项目实战-Api的解决方案
  • 责任链模式的两种实现
  • “十年磨一剑”--有赞的HBase平台实践和应用之路 ...
  • 1.Ext JS 建立web开发工程
  • 好程序员web前端教程分享CSS不同元素margin的计算 ...
  • 组复制官方翻译九、Group Replication Technical Details
  • ​无人机石油管道巡检方案新亮点:灵活准确又高效
  • # MySQL server 层和存储引擎层是怎么交互数据的?
  • #define用法
  • #includecmath
  • #图像处理
  • #我与Java虚拟机的故事#连载15:完整阅读的第一本技术书籍
  • (1)STL算法之遍历容器
  • (2)STL算法之元素计数
  • (20050108)又读《平凡的世界》
  • (C#)if (this == null)?你在逗我,this 怎么可能为 null!用 IL 编译和反编译看穿一切
  • (Spark3.2.0)Spark SQL 初探: 使用大数据分析2000万KF数据
  • (附源码)springboot家庭财务分析系统 毕业设计641323
  • (附源码)springboot金融新闻信息服务系统 毕业设计651450
  • (十三)Maven插件解析运行机制
  • (学习日记)2024.03.12:UCOSIII第十四节:时基列表
  • * 论文笔记 【Wide Deep Learning for Recommender Systems】
  • .\OBJ\test1.axf: Error: L6230W: Ignoring --entry command. Cannot find argumen 'Reset_Handler'
  • .bat文件调用java类的main方法
  • .net core 6 使用注解自动注入实例,无需构造注入 autowrite4net