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],
]

是一种穷举遍历的思想;

自己的代码:(递归 DFS)

Runtime: 39 ms, faster than 37.50% of Java online submissions for Combinations.

Memory Usage: 43.8 MB, less than 26.50% of Java online submissions for Combinations.

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;class Solution {public static List<List<Integer>> combine(int n, int k) {List<List<Integer>> results = new ArrayList<>();List<Integer> tempList = new ArrayList<>();  helper(results,tempList,1,n,k);return results;}public static void helper(List<List<Integer>> results ,List<Integer> tempList,int start,int n, int k) {if(k == 0) {List<Integer> list = new ArrayList<>();for(Integer i : tempList) {list.add(i);}results.add(list);return;}for(int i=start;i<=n;i++) {tempList.add(i);// not add(start)helper(results,tempList,i+1,n,k-1); // 参数三:是i+1,不是start+1tempList.remove(new Integer(i));}}public static void main(String[] args) {int n = 4;int k = 2;List<List<Integer>> list = combine(n,k);System.out.println(list);}
}

  递归思想:(分解成子问题)

   0)因为不确定k的大小,所以想到用递归

1)helper(start,n,k)的功能就是获得从start到n的数,组成的长度为k的所有可能结果

2)那么helper(start+1,n,k-1)的功能就是获得从start+1到n的数,组成的长度为k-1的所有可能结果

自己的代码2

import java.util.ArrayList;
import java.util.List;public class WelcomeApp {private static int count = 0;private static StringBuilder sb = new StringBuilder();private static List<String> lists = new ArrayList<>();// 获得n选k的全部组合public static void getK(int n, int k, int index,int start) {if(index > 3) {lists.add(sb.toString());count++;return;}for(int i=start;i<=n-k+1;i++) {String temp = i+" ";sb.append(temp);getK(n, k-1, index+1,i+1); // 注意第2 3 4个参数的设置;sb.delete(sb.length()-temp.length(), sb.length()); // 这句回溯一定不能少}}public static void main(String[] args) {int n=12;// 1,2,3,4,5int k=3;//取出3个数getK(n, k, 1,1);for(String str : lists) { System.out.println(str);}System.out.println("count = "+count);}}

小结:

a)应用DFS进行穷举遍历时,回溯的步骤是一定不能少的

别人的代码:

方法一:递归 + 回溯(和我的思路一模一样)

class Solution {public static List<List<Integer>> combine(int n, int k) {List<List<Integer>> combs = new ArrayList<List<Integer>>();combine(combs, new ArrayList<Integer>(), 1, n, k);return combs;}public static void combine(List<List<Integer>> combs, List<Integer> comb, int start, int n, int k) {if(k==0) {combs.add(new ArrayList<Integer>(comb)); // 直接通过构造函数,复制一个listreturn;}for(int i=start;i<=n;i++) {comb.add(i);combine(combs, comb, i+1, n, k-1);comb.remove(comb.size()-1);  // 使用的是remove(index)这个方法}}
}

1)时间复杂度:The time complexity is "n times n choose k".

"n choose k" equals (n!/((n-k)! * k!)). In full notation is O(n * (n!/((n-k)! * k!))).

We will have "n choose k" combinations and in each call we will do O(n) work to copy the array to the answer.

和方法一相同的思路的Python解法:

class Solution(object):def combine(self, n, k):""":type n: int:type k: int:rtype: List[List[int]]"""res = []def gen(i, tmp):if len(tmp) == k:res.append(list(tmp))returnif i > n:returnfor j in range(i, n+1):tmp.append(j)gen(j+1, tmp)tmp.pop()gen(1, [])return res
class Solution(object):def combine(self, n, k):""":type n: int:type k: int:rtype: List[List[int]]"""results = []result = []def DFS(results, result, start, n, k):if(k==len(result)):results.append(copy.deepcopy(result))  # python append()与深拷贝、浅拷贝应该注意,此处有一个大坑return  for i in range(start,n+1,1):result.append(i)DFS(results, result, i+1, n, k)result.pop()DFS(results, result, 1, n, k)return results
"""
[Python]_DFS_beats 97.24%The key is to stop earlier (i.e. prune the search space) if the number of numbers could be selected (n-i) is less than the number of numbers we need to select (k).当剩余的可以被选择的数的个数n-i,小于我们所需要选择的数的个数k,那么就提前终止,不用递归函数再进行下去
"""class Solution:def combine(self, n: 'int', k: 'int') -> 'List[List[int]]':res = []cur = []self.combine_helper(n, k, 0, cur, res)return resdef combine_helper(self, n, k, idx, cur, res):if k == 0:res.append(cur[:])else:for i in range(idx, n):if k > (n-i):breakval = i + 1cur.append(val)self.combine_helper(n, k-1, i+1, cur, res)cur.pop()

LeetCode之77. Combinations相关推荐

  1. [LeetCode Python3]77. Combinations回溯

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

  2. 【LeetCode】77. Combinations 解题报告(Python C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:递归 方法二:回溯法 日期 题目地址:htt ...

  3. Leetcode Golang 77. Combinations.go

    思路 看到这个词,马上就想到了回溯 code func combine(n int, k int) [][]int {var res [][]inthelper(&res, []int{}, ...

  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 77. Combinations 组合

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

  6. leetcode算法题--Combinations

    原题链接:https://leetcode.com/problems/combinations/ class Solution {public:vector<vector<int>& ...

  7. 【DFS】LeetCode 17. Letter Combinations of a Phone Number

    LeetCode 17. Letter Combinations of a Phone Number Solution1:我的答案 利用8皇后同样的方法,回溯+递归 时间复杂度O(3n)O(3n)O( ...

  8. 77. Combinations(组合)

    题目链接:https://leetcode.com/problems/combinations/ 思路: 回溯,直接用回溯递归,注意边界条件. AC 1ms 100% Java: class Solu ...

  9. LeetCode | 0017. Letter Combinations of a Phone Number电话号码的字母组合【Python】

    LeetCode 0017. Letter Combinations of a Phone Number电话号码的字母组合[Medium][Python][回溯][DFS][暴力] Problem L ...

最新文章

  1. vs2013编译 protoBuffer编译出现的问题
  2. 《卫生信息基本数据集编制规范》等23项行业标准的通告
  3. django oracle数据库配置,django连接oracle时setting 配置方法
  4. python 程序1【登录接口】
  5. U盘安装Ubuntu14.04
  6. Mysql迁移到Oracle方法
  7. 用matlab跑神经网络模型,怎样在matlab里建立一个BP神经网络模型?
  8. datastax.repo_使用Datastax Java驱动程序与Cassandra进行交互
  9. php 图片合成,PHP中多张图片合成一张图片例子
  10. python输出布尔值true_关于python中bool类型的重要细节
  11. 服务器4通道性能相当于多少人民币,有钱人的世界我们不懂,组装电脑花费百来万,跑分世界第四...
  12. 如何使用SPSS判断数据的正态分布
  13. iframe 重新加载
  14. c语言经典笔试100题,100条经典C语言笔试题目(全).doc
  15. 蓝桥杯 分解质因数 C语言
  16. 并行优化:OpenMP
  17. caffe学习笔记2:net forward与backward
  18. 【SCA-CNN 解读】空间与通道注意力:Spatial and Channel-wise Attention
  19. 基于树莓派4B搭建64位树莓派系统
  20. 计算机论文免费模板,1.计算机专业毕业论文模板

热门文章

  1. 计算机教案动作按钮,自定义动画及动作设置》教学设计
  2. [生存志] 第84节 列子淡泊号冲虚
  3. gb和gib的区别_KB/KiB,MB/MiB,GB/GiB,它们有区别吗?
  4. 【SQL】获取今天昨天本周上周本月上月本年去年的起止日期
  5. pywinauto入门—使用pywinauto操作PC版微信发送消息
  6. 58同城2021校招笔试-二叉树遍历
  7. MP的增删改查基本操作
  8. 《Python自然语言处理(第二版)-Steven Bird等》学习笔记:第05章 分类和标注词汇
  9. 根据传入日期 往前或者往后 顺延月份
  10. 蓝桥杯单片机第四届省赛题详细讲解(模拟智能灌溉系统)