2026.01.22 组合 &

https://leetcode.cn/problems/combinations/description/

python 复制代码
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        ans = []
        path = []

        def dfs(n: int) -> None:
            d = k - len(path)
            # d表示还需要的长度
            if d == 0:
                ans.append(path.copy())
                return
            for i in range(n, d - 1, -1):
                # 左开右闭,当剩余的数字不足够d(所需要的长度)时结束循环
                path.append(i)
                dfs(i - 1)
                path.pop()
        dfs(n)
        return ans

https://leetcode.cn/problems/combination-sum-iii/description/

python 复制代码
class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        ans = []
        path = []
        curSum = 0
        def dfs(i:int) -> None:
            nonlocal curSum
            d = n - curSum
            if k - len(path) > i or d < 0:
                # 剪枝
                return
            if d == 0 and len(path) == k:
                ans.append(path[:])
                return
            
            for j in range(i, 0, -1):
                curSum += j
                path.append(j)
                dfs(j - 1)
                curSum -= j
                path.pop()
        dfs(9)
        return ans

https://leetcode.cn/problems/letter-combinations-of-a-phone-number/description/

python 复制代码
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits: return []
        res = []
        phone = {'2':['a','b','c'],
                 '3':['d','e','f'],
                 '4':['g','h','i'],
                 '5':['j','k','l'],
                 '6':['m','n','o'],
                 '7':['p','q','r','s'],
                 '8':['t','u','v'],
                 '9':['w','x','y','z']}

        def backtrack(conbination, nextdigit):
            if len(nextdigit) == 0:
                res.append(conbination)
                return
            else:
                for letter in phone[nextdigit[0]]:
                    backtrack(conbination + letter, nextdigit[1:])
        backtrack('', digits)
        return res
相关推荐
小豆庄2 小时前
视频遮罩追踪退场后ID撞号的排查—多目标场景下的失效
opencv·算法·bug·视频·python3.11
Tisfy2 小时前
LeetCode 3882.网格图中最小异或路径:动态规划
算法·leetcode·动态规划
D e re k ZH3 小时前
P5025 [SNOI2017] 炸弹
c++·算法
A boy CDEF girl3 小时前
算法题专栏:优选算法
数据结构·算法·leetcode
没落之王3 小时前
三易五行看宋朝的三界确立
大数据·人工智能·算法
坤坤子吖4 小时前
算法学习——单调队列
开发语言·c++·笔记·学习·算法
Js.Tx5 小时前
【具体数学 Concrete Mathematics】2.1.5 一般性的方法
算法·具体数学
秋天的怀念_David7 小时前
算法一千零一夜 · 作品相关:版权与致谢声明
程序人生·算法·学习方法
揽星河..7 小时前
【C语言】数组
c语言·开发语言·算法
careathers7 小时前
【数据结构】基于比较的排序算法 - 选择排序
数据结构·算法·排序算法