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
相关推荐
偷吃的耗子17 分钟前
【CNN算法理解】:CNN平移不变性详解:数学原理与实例
人工智能·算法·cnn
dazzle1 小时前
机器学习算法原理与实践-入门(三):使用数学方法实现KNN
人工智能·算法·机器学习
那个村的李富贵1 小时前
智能炼金术:CANN加速的新材料AI设计系统
人工智能·算法·aigc·cann
张张努力变强2 小时前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
万岳科技系统开发2 小时前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
张登杰踩2 小时前
MCR ALS 多元曲线分辨算法详解
算法
YuTaoShao2 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
波波0072 小时前
每日一题:.NET 的 GC是如何分代工作的?
算法·.net·gc
风暴之零2 小时前
变点检测算法PELT
算法
深鱼~2 小时前
视觉算法性能翻倍:ops-cv经典算子的昇腾适配指南
算法·cann