LeetCode #77 组合
一、题目
二、思路
回溯,可以剪枝,剪枝条件是for循环选择的起始位置之后的元素个数 已经不足 我们需要的元素个数了,那么就没有必要搜索了,例如n=4,k=3,从3开始是不能形成有3个数的组合,只需要从1、2开始搜
搜索起点的上界 + 接下来要选择的元素个数 - 1 = n,
例如n = 4,k = 3,path.size为1时,还要选择2个数,最大的搜索起点为3,最后一个组合为【3,4】
接下来要选择的元素个数为k - path.size()
所以搜索起点的上界 = n - (k - path.size() + 1)
n - (k - path.size() + 1)
三、代码实现
public List<List<Integer>> combine(int n, int k) {List<Integer> path = new ArrayList<>();List<List<Integer>> res = new ArrayList<>();combineDfs(n,k,path,res,1);return res;}private void combineDfs(int n, int k, List<Integer> path, List<List<Integer>> res, int index) {if (path.size() == k) {res.add(new ArrayList<>(path));return;}for (int i = index; i <= n - (k - path.size()) + 1; i++) {path.add(i);combineDfs(n,k,path,res,i + 1);path.remove(path.size()-1);}}
LeetCode #77 组合相关推荐
- LeetCode.77. 组合
LeetCode.77. 组合 难度:中等 这道题属于回溯的经典题目: 回溯模板: void backtracking(参数) {if (终止条件) {存放结果;return;}for (选择:本层集 ...
- leetcode:77.组合
77. 组合 来源:力扣(LeetCode) 链接: https://leetcode.cn/problems/combinations 给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 ...
- LeetCode 77. 组合 | Python
77. 组合 题目来源:力扣(LeetCode)https://leetcode-cn.com/problems/combinations 题目 给定两个整数 n 和 k,返回 1 - n 中所有可能 ...
- Java实现 LeetCode 77 组合
77. 组合 给定两个整数 n 和 k,返回 1 - n 中所有可能的 k 个数的组合. 示例: 输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], ...
- LeetCode 77. 组合(回溯)
1. 题目 给定两个整数 n 和 k,返回 1 - n 中所有可能的 k 个数的组合. 示例:输入: n = 4, k = 2 输出: [[2,4],[3,4],[2,3],[1,2],[1,3],[ ...
- LeetCode 77 组合 -- 回溯法
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/combinations 题意: 给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 ...
- Leetcode 77.组合
组合 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合. 示例: 输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1 ...
- LeetCode 77.组合求和
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合. candidates 中的数字可以无限制重复被选 ...
- leetcode 77. 组合 思考分析
目录 1.题目 2.回溯法思路 3.参考其他思路,更深入了解这个问题 4.剪枝优化 可能需要回顾到的知识文章: 1.常用算法总结(穷举法.贪心算法.递归与分治算法.回溯算法.数值概率算法) 2.回溯法 ...
- LeetCode 77 组合
题目描述 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合. 题解 深度优先搜索 代码 class Solution {public:void dfs(vector< ...
最新文章
- “大型票务系统”和“实物电商系统”的数据库选型
- Linux常用命令--echo
- python pip-python的pip安装以及使用教程
- DPKG命令与软件安装、APT
- [PHP] PHP调用IMAP协议读取邮件类库
- 使用Maven Jenkins和JMeter自动化测试
- 计算机地址码特点,电脑摇头灯的地址码的设定问题你必须要注意的
- Win7下使用U盘安装linux Ubuntu16.04双系统图文教程
- Redis系统性介绍
- 爱因斯坦谈教育,放在首位的该是什么?
- normalize函数_Pandas 数据处理(一) —— 几个简单函数掌握!
- 阿里云服务器内核编译升级
- cad图纸怎么看懂_CAD图纸太大,打开的时候很卡怎么办?教你如何给图纸瘦身
- Haproxy+Keepalived+Nginx
- [Java][Android][Process] 暴力的服务可以解决一切,暴力的方式执行命令行语句
- 【解决方案】ArcGIS License Manager启动失败
- u盘的大小在计算机无法显示,Win10电脑插入U盘后没有显示可用容量打不开无法读取如何解决...
- 生成小程序二维码(草料)
- Python量化分析,计算KDJ
- 阿里云账号个人实名认证教程