• dfs全排列总结


    17. Letter Combinations of a Phone Number

    Medium

    12161744Add to ListShare

    Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order

    A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

    Example 1:

    Input: digits = "23"
    Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
    

    Example 2:

    Input: digits = ""
    Output: []
    

    Example 3:

    Input: digits = "2"
    Output: ["a","b","c"]
    

    Constraints:

    • 0 <= digits.length <= 4
    • digits[i] is a digit in the range ['2', '9'].

    Accepted

    1.3M

    Submissions

    2.4M

    遇到这样的题首先可以画图。全排列分为两种,2叉树和k叉树,这题就是个k叉树。

    比如输入“23”,即可画出下图。

    由此我们可以把他转换成dfs问题,只要把k叉树遍历即可。

    首先考虑遍历的终止条件,就是每个digit都访问到了的情况,所以我们使用index来记录目前访问了几位digit

    在访问时用cur 字符串来记录当前遍历路径所生成的字符串

     

    1. class Solution:
    2. def letterCombinations(self, digits: str) -> List[str]:
    3. if not digits:
    4. return None
    5. self.res = []
    6. self.hm = {"2":"abc","3":"def",
    7. "4":"ghi","5":"jkl","6":"mno"
    8. ,"7":"pqrs","8":"tuv","9":"wxyz"}
    9. self.dfs(digits,"",0)
    10. return self.res
    11. def dfs(self,digits,cur,index):
    12. if index == len(digits):
    13. self.res.append(cur)
    14. return
    15. for c in self.hm[digits[index]]:
    16. self.dfs(digits,cur+c,index+1)

    78. Subsets

    Medium

    11655169Add to ListShare

    Given an integer array nums of unique elements, return all possible subsets (the power set).

    The solution set must not contain duplicate subsets. Return the solution in any order.

    Example 1:

    Input: nums = [1,2,3]
    Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
    

    Example 2:

    Input: nums = [0]
    Output: [[],[0]]
    

    Constraints:

    • 1 <= nums.length <= 10
    • -10 <= nums[i] <= 10
    • All the numbers of nums are unique.

     这个题是一个二叉树问题,对于列表里的每个元素,我们都可以选择加入或不加入列表。

     使用dfs 即可,因为有回溯所以每次加完了需要pop

    1. class Solution:
    2. def subsets(self, nums: List[int]) -> List[List[int]]:
    3. self.res = []
    4. self.dfs(nums,0,[])
    5. return self.res
    6. def dfs(self,nums,index,cur):
    7. if index == len(nums):
    8. self.res.append(list(cur))
    9. return
    10. self.dfs(nums, index + 1, cur)
    11. cur.append(nums[index])
    12. self.dfs(nums, index + 1, cur)
    13. cur.pop()

  • 相关阅读:
    IntelliJ IDEA 常用的插件
    Lodop 实现局域网打印
    字符串常量池与StringBuilder
    SAP 20策略测试简介
    uniapp中u-input点击事件失效
    全网最详细的bert Bert文本分类教程 数据+完整代码 可直接运行
    小小总结之二分查找三种情况
    ACM-ICPC Northeastern European Regional Contest (NEERC 15) -Generators
    带你快速掌握Linux最常用的命令(图文详解)- 最新版(面试笔试常考)
    【数据库应用-1】——CDA
  • 原文地址:https://blog.csdn.net/mayuqing98/article/details/126515859