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 字符串来记录当前遍历路径所生成的字符串

 

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return None
        self.res = []
        self.hm = {"2":"abc","3":"def",
                "4":"ghi","5":"jkl","6":"mno"
                ,"7":"pqrs","8":"tuv","9":"wxyz"}
        self.dfs(digits,"",0)
        return self.res
    def dfs(self,digits,cur,index):
        
        if index == len(digits):
            self.res.append(cur)
            return
        for c in self.hm[digits[index]]:  
            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

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        self.res = []
        self.dfs(nums,0,[])
        return self.res
    def dfs(self,nums,index,cur):
        if index == len(nums):
            self.res.append(list(cur))
            return
        self.dfs(nums, index + 1, cur)
        cur.append(nums[index])
        self.dfs(nums, index + 1, cur)
        cur.pop()
       
        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值