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
相关推荐
FJW0208142 小时前
Python排序算法
python·算法·排序算法
钮钴禄·爱因斯晨2 小时前
机器学习(二):KNN算法简介及API介绍(分类、回归)
人工智能·算法·机器学习·分类·回归
如此这般英俊2 小时前
第八章-排序
数据结构·算法·排序算法
源代码•宸2 小时前
Leetcode—146. LRU 缓存【中等】(哈希表+双向链表)
后端·算法·leetcode·缓存·面试·golang·lru
郭涤生2 小时前
AWB算法基础理解
人工智能·算法·计算机视觉
hetao17338372 小时前
2026-01-21~22 hetao1733837 的刷题笔记
c++·笔记·算法
Hcoco_me2 小时前
大模型面试题91:合并访存是什么?原理是什么?
人工智能·深度学习·算法·机器学习·vllm
2501_901147832 小时前
零钱兑换——动态规划与高性能优化学习笔记
学习·算法·面试·职场和发展·性能优化·动态规划·求职招聘
狐574 小时前
2026-01-22-LeetCode刷题笔记-3507-移除最小数对使数组有序I
笔记·leetcode