【leetcode】77.组合

文章目录

    • 题目
    • 题解
      • [1. 回溯](#1. 回溯)
      • [2. 剪枝优化](#2. 剪枝优化)

题目

77.组合

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

你可以按 任何顺序 返回答案。

示例 1:

输入:n = 4, k = 2

输出:

\[2,4\], \[3,4\], \[2,3\], \[1,2\], \[1,3\], \[1,4\],

示例 2:

输入:n = 1, k = 1

输出:[[1]]

题解

1. 回溯

python 复制代码
class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        result = []
        path = []
        start = 1
        def backtracking(n, k, path, start, result):
            if len(path) == k:
                result.append(path[:])
                return 
            
            for i in range(start, n + 1):
                path.append(i)
                backtracking(n, k, path, i + 1, result)
                path.pop()


        if n == 1:
            return [[1]]
        backtracking(n, k, path, start, result)
        return result
        

2. 剪枝优化

python 复制代码
n + 1 - (k - len(path)) + 1
python 复制代码
class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        result = []
        path = []
        start = 1
        def backtracking(n, k, path, start, result):
            if len(path) == k:
                result.append(path[:])
                return 
            
            for i in range(start, n + 1 - (k - len(path)) + 1):
                path.append(i)
                backtracking(n, k, path, i + 1, result)
                path.pop()


        if n == 1:
            return [[1]]
        backtracking(n, k, path, start, result)
        return result
        
相关推荐
董董灿是个攻城狮10 小时前
AI视觉连载8:传统 CV 之边缘检测
算法
AI软著研究员17 小时前
程序员必看:软著不是“面子工程”,是代码的“法律保险”
算法
FunnySaltyFish17 小时前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
颜酱18 小时前
理解二叉树最近公共祖先(LCA):从基础到变种解析
javascript·后端·算法
地平线开发者1 天前
SparseDrive 模型导出与性能优化实战
算法·自动驾驶
董董灿是个攻城狮1 天前
大模型连载2:初步认识 tokenizer 的过程
算法
地平线开发者1 天前
地平线 VP 接口工程实践(一):hbVPRoiResize 接口功能、使用约束与典型问题总结
算法·自动驾驶
罗西的思考1 天前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
HXhlx2 天前
CART决策树基本原理
算法·机器学习
Wect2 天前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲
前端·算法·typescript