题目地址:


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解法相关推荐

  1. LeetCode 77 组合 -- 回溯法

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/combinations 题意: 给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 ...

  2. Leetcode 77. Combinations 组合

    Leetcode 77. Combinations 组合 标签 : Leetcode 题目地址: https://leetcode-cn.com/problems/combinations/ 题目描述 ...

  3. LeetCode算法总结-回溯法与深度优先搜索

    转载自  LeetCode算法总结-回溯法与深度优先搜索 回溯法(探索与回溯法)是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标.但当探索到某一步时,发现原先选择并不优或达不到目标,就退 ...

  4. 【DFS】LeetCode 77. Combinations

    LeetCode 77. Combinations Solution1:我的答案 DFS,时间复杂度O(n!)O(n!)O(n!),空间复杂度O(n)O(n)O(n) class Solution { ...

  5. 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 ...

  6. 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 ...

  7. [LeetCode Python3]77. Combinations回溯

    77. Combinations class Solution:def __init__(self):self.res = []def trackback(self, track, index, n, ...

  8. LeetCode | 0077. Combinations组合【Python】

    LeetCode 0077. Combinations组合[Medium][Python][回溯] Problem LeetCode Given two integers n and k, retur ...

  9. LeetCode 804 Unique Morse Code Words--python,java解法

    题目地址:Unique Morse Code Words - LeetCode Difficulty:easy Acceptance:74.1% International Morse Code de ...

最新文章

  1. C# 运算符及条件控制语句
  2. HDU5977 Garden of Eden 【FMT】【树形DP】
  3. windows下修改tomcat的startup.bat脚本文件后台运行
  4. 大型网站技术架构(三)架构核心要素
  5. 剑灵火龙区服务器位置,剑灵双线火龙新区活动介绍
  6. [转载] Java 单例(Singleton)类
  7. 一键安装lamp环境 centos
  8. 数据结构系列-队列的基本操作
  9. 2017陕西省网络空间安全技术大赛_Crypto_crypt1_Writeup
  10. 从三大方面,分析 to B和 to C产品的区别与联系
  11. samba使用root用户连接
  12. 线下商家卖货难、拓客难、引流难,不如学习一下怎么结合O2O电商
  13. JVM垃圾回收说为学日益,为道日损
  14. win10系统显示打印机未连接到服务器,win10系统无法连接到打印机的解决方法
  15. 如何用R包做词频统计图(词云)?
  16. 猿人学第二题,手撕OB混淆给你看(step06-控制流平坦化)
  17. 生活 RH阴性血 AB型
  18. RoboMaster遥控器调参以及左上角拨轮开启教程
  19. 计算机算法讲解的ppt,智能计算几种经典算法解析.ppt
  20. UG10.0汽车冲压连续模具设计视频教程 AutoForm分析

热门文章

  1. Failure [DELETE_FAILED_INTERNAL_ERROR]的解决办法
  2. TMB计算的小工具-calculate_TMB.exe
  3. 西湖大学鞠峰组招聘微生物组学、病毒组学与生物信息学博士后
  4. ISME: 中科院南京土壤所褚海燕组揭示关键菌群的生物多样性决定作物产量
  5. Maptree-层级结构数据展示的绝佳尝试
  6. Nature Method :Rob Knight发布Striped UniFrac算法轻松分析微生物组大数据
  7. Python使用matplotlib可视化面积图(Area Chart)、通过给坐标轴和曲线之间的区域着色可视化面积图、在面积图的指定区域添加箭头和数值标签
  8. R语言构建随机森林模型randomForest分类模型并评估模型在测试集和训练集上的效果(accuray、F1、偏差Deviance):随机森林在Bagging算法的基础上加入了列采样(分枝特征随机)
  9. 什么是数据库视图(view),视图(view)优缺点是什么?
  10. python使用pandas基于时间条件查询多个oracle数据表