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
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()
-