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
相关推荐
小辉同志18 小时前
139. 单词拆分
算法·动态规划
oem11018 小时前
C++中的访问者模式变体
开发语言·c++·算法
IronMurphy18 小时前
【算法二十七】230. 二叉搜索树中第 K 小的元素 199. 二叉树的右视图
算法·深度优先
暮冬-  Gentle°18 小时前
C++中的工厂方法模式
开发语言·c++·算法
沐硕18 小时前
《基于改进协同过滤与多目标优化的健康饮食推荐系统设计与实现》
java·python·算法·fastapi·多目标优化·饮食推荐·改进协同过滤
Z9fish18 小时前
sse哈工大C语言编程练习47
c语言·数据结构·算法
nglff19 小时前
蓝桥杯抱佛脚第一天|简单模拟,set,map的使用
算法·职场和发展·蓝桥杯
仟濹19 小时前
【算法打卡day27(2026-03-19 周四)】蓝桥云课中Lv.1难度中的绝大部分题
算法·蓝桥杯
罗湖老棍子19 小时前
滑动窗口与双调队列:幕布覆盖问题(定右缩左满分板子)改编自LeetCode 1438
算法·滑动窗口·单调队列
CoovallyAIHub19 小时前
ICLR 2026 | MedAgent-Pro:用 Agent 工作流模拟临床医生的循证诊断过程
深度学习·算法·计算机视觉