LeetCode 77. Combinations--回溯法,-Python,Java解法
题目地址:
Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
Example:
Input: n = 4, k = 2
Output:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4],
]
这道题可以用回溯法来做。
Python回溯解法:
class Solution:def combine(self, n: int, k: int) -> List[List[int]]:def backtrack(first = 1, curr = []):# if the combination is doneif len(curr) == k: output.append(curr[:])for i in range(first, n + 1):# add i into the current combinationcurr.append(i)# use next integers to complete the combinationbacktrack(i + 1, curr)# backtrackcurr.pop()output = []backtrack()return output
第二种解法是使用词典的组合,Python代码如下:
class Solution:def combine(self, n: int, k: int) -> List[List[int]]:# init first combinationnums = list(range(1, k + 1)) + [n + 1]output, j = [], 0while j < k:# add current combinationoutput.append(nums[:k])# increase first nums[j] by one# if nums[j] + 1 != nums[j + 1]j = 0while j < k and nums[j + 1] == nums[j] + 1:nums[j] = j + 1j += 1nums[j] += 1return output
java 回溯解法:
class Solution {List<List<Integer>> output = new LinkedList();int n;int k;public void backtrack(int first, LinkedList<Integer> curr) {// if the combination is doneif (curr.size() == k)output.add(new LinkedList(curr));for (int i = first; i < n + 1; ++i) {// add i into the current combinationcurr.add(i);// use next integers to complete the combinationbacktrack(i + 1, curr);// backtrackcurr.removeLast();}}public List<List<Integer>> combine(int n, int k) {this.n = n;this.k = k;backtrack(1, new LinkedList<Integer>());return output;}
}
java 的改进解法:
class Solution {public List<List<Integer>> combine(int n, int k) {// init first combinationLinkedList<Integer> nums = new LinkedList<Integer>();for(int i = 1; i < k + 1; ++i)nums.add(i);nums.add(n + 1);List<List<Integer>> output = new ArrayList<List<Integer>>();int j = 0;while (j < k) {// add current combinationoutput.add(new LinkedList(nums.subList(0, k)));// increase first nums[j] by one// if nums[j] + 1 != nums[j + 1]j = 0;while ((j < k) && (nums.get(j + 1) == nums.get(j) + 1))nums.set(j, j++ + 1);nums.set(j, nums.get(j) + 1);}return output;}
}
LeetCode 77. Combinations--回溯法,-Python,Java解法相关推荐
- LeetCode 77 组合 -- 回溯法
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/combinations 题意: 给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 ...
- Leetcode 77. Combinations 组合
Leetcode 77. Combinations 组合 标签 : Leetcode 题目地址: https://leetcode-cn.com/problems/combinations/ 题目描述 ...
- LeetCode算法总结-回溯法与深度优先搜索
转载自 LeetCode算法总结-回溯法与深度优先搜索 回溯法(探索与回溯法)是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标.但当探索到某一步时,发现原先选择并不优或达不到目标,就退 ...
- 【DFS】LeetCode 77. Combinations
LeetCode 77. Combinations Solution1:我的答案 DFS,时间复杂度O(n!)O(n!)O(n!),空间复杂度O(n)O(n)O(n) class Solution { ...
- LeetCode 51. N-Queens--回溯法 pyhon,java,c++解法
题目地址: The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two q ...
- LeetCode 85. Maximal Rectangle --python,java解法
题目地址: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1 ...
- [LeetCode Python3]77. Combinations回溯
77. Combinations class Solution:def __init__(self):self.res = []def trackback(self, track, index, n, ...
- LeetCode | 0077. Combinations组合【Python】
LeetCode 0077. Combinations组合[Medium][Python][回溯] Problem LeetCode Given two integers n and k, retur ...
- LeetCode 804 Unique Morse Code Words--python,java解法
题目地址:Unique Morse Code Words - LeetCode Difficulty:easy Acceptance:74.1% International Morse Code de ...
最新文章
- C# 运算符及条件控制语句
- HDU5977 Garden of Eden 【FMT】【树形DP】
- windows下修改tomcat的startup.bat脚本文件后台运行
- 大型网站技术架构(三)架构核心要素
- 剑灵火龙区服务器位置,剑灵双线火龙新区活动介绍
- [转载] Java 单例(Singleton)类
- 一键安装lamp环境 centos
- 数据结构系列-队列的基本操作
- 2017陕西省网络空间安全技术大赛_Crypto_crypt1_Writeup
- 从三大方面,分析 to B和 to C产品的区别与联系
- samba使用root用户连接
- 线下商家卖货难、拓客难、引流难,不如学习一下怎么结合O2O电商
- JVM垃圾回收说为学日益,为道日损
- win10系统显示打印机未连接到服务器,win10系统无法连接到打印机的解决方法
- 如何用R包做词频统计图(词云)?
- 猿人学第二题,手撕OB混淆给你看(step06-控制流平坦化)
- 生活 RH阴性血 AB型
- RoboMaster遥控器调参以及左上角拨轮开启教程
- 计算机算法讲解的ppt,智能计算几种经典算法解析.ppt
- UG10.0汽车冲压连续模具设计视频教程 AutoForm分析
热门文章
- Failure [DELETE_FAILED_INTERNAL_ERROR]的解决办法
- TMB计算的小工具-calculate_TMB.exe
- 西湖大学鞠峰组招聘微生物组学、病毒组学与生物信息学博士后
- ISME: 中科院南京土壤所褚海燕组揭示关键菌群的生物多样性决定作物产量
- Maptree-层级结构数据展示的绝佳尝试
- Nature Method :Rob Knight发布Striped UniFrac算法轻松分析微生物组大数据
- Python使用matplotlib可视化面积图(Area Chart)、通过给坐标轴和曲线之间的区域着色可视化面积图、在面积图的指定区域添加箭头和数值标签
- R语言构建随机森林模型randomForest分类模型并评估模型在测试集和训练集上的效果(accuray、F1、偏差Deviance):随机森林在Bagging算法的基础上加入了列采样(分枝特征随机)
- 什么是数据库视图(view),视图(view)优缺点是什么?
- python使用pandas基于时间条件查询多个oracle数据表