前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-77-组合

leetcode-77-组合

作者头像
Spaceack
发布2020-11-04 14:43:50
5310
发布2020-11-04 14:43:50
举报
文章被收录于专栏:编程使我快乐编程使我快乐

题目描述

给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。

示例

示例 1: 来源:力扣(LeetCode) 链接:


解题思路

虽然是中等题,但是使用python内置函数,就简单了。

组合,没有重复的情况(不放回抽样组合) 使用 itertools.combinations 方法,

代码语言:javascript
复制
def combine(self, n: int, k: int) -> List[List[int]]:
    result = []
    for i in itertools.combinations(list(range(1, n+1)), k):
        result.append(list(i))
    return result
    # [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] 6

其它方法:

组合,有重复的情况(放回抽样组合) 使用 itertools.combinations_with_replacement 方法,

代码语言:javascript
复制
def combine(self, n: int, k: int) -> List[List[int]]:
    result = []
    for i in itertools.combinations_with_replacement(list(range(1, n+1)), k):
        result.append(list(i))
    return result
    # [[1, 1], [1, 2], [1, 3], [1, 4], [2, 2], [2, 3], [2, 4], [3, 3], [3, 4], [4, 4]] 10
代码语言:javascript
复制
- 排列 (不放回抽样排列)使用 `itertools.permutations` 方法,

    1
2
3
4
5
6
def combine(self, n: int, k: int) -> List[List[int]]:
    result = []
    for i in itertools.permutations(list(range(1, n+1)), k):
        result.append(list(i))
    return result
    # [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]] 12


- 笛卡尔积 (有放回抽样排列) 使用 `itertools.product` 方法,
    1
2
3
4
5
6
def combine(self, n: int, k: int) -> List[List[int]]:
    result = []
    for i in itertools.product(list(range(1, n+1)), repeat = k):
        result.append(list(i))
    return result
    # [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [2, 3], [2, 4], [3, 1], [3, 2], [3, 3], [3, 4], [4, 1], [4, 2], [4, 3], [4, 4]] 16


`combinations`和`permutations`返回的是对象地址, 需要将iterator 转换成list 即可

题解1:

执行用时:48 ms, 在所有 Python3 提交中击败了95.61%的用户

内存消耗:14.8 MB, 在所有 Python3 提交中击败了98.26%的用户

代码语言:javascript
复制
import itertools
from typing import List

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        result = []
        for i in itertools.combinations(list(range(1, n+1)), k):
            result.append(list(i))
        return result
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档