题目:17. 电话号码的字母组合
我的感悟:
- 一时间没理解没关系,只要不放弃,就会成长!!!
理解难点:
- index是独立集合的起点,需要理解它。
- 有些东西就是时间的积累
代码难点:
代码示例:
class Solution:
def __init__(self):
self.letterMap = [
"", # 0
"", # 1
"abc", # 2
"def", # 3
"ghi", # 4
"jkl", # 5
"mno", # 6
"pqrs", # 7
"tuv", # 8
"wxyz" # 9
]
def letterCombinations(self, digits: str) -> List[str]:
if len(digits)==0:
return []
res = []
self.backtracking(digits,0,[],res)
return res
def backtracking(self,digits,index,path,res):
if len(path) == len(digits):
res.append("".join(path))
return
wight = self.letterMap[int(digits[index])]
for i in range(len(wight)):
path.append(wight[i])
self.backtracking(digits,index+1,path,res)
path.pop()
补充注释:
class Solution:
def __init__(self):
self.letterMap = [
"", # 0
"", # 1
"abc", # 2
"def", # 3
"ghi", # 4
"jkl", # 5
"mno", # 6
"pqrs", # 7
"tuv", # 8
"wxyz" # 9
]
def letterCombinations(self, digits: str) -> List[str]:
# 对特殊做处理
if len(digits) == 0:
return []
# 正常走回溯法
res = []
self.backtracking(digits, 0, [], res)
return res
def backtracking(self, digits, index, path, res):
# 1.深度达到要求就跳出循环
if len(path) == len(digits):
res.append("".join(path))
return
# 2.宽度 . 横向遍历
wight = self.letterMap[int(digits[index])] # 宽度,是指每个小集合的宽度 "abc"的宽度,... "wxyz"的宽度
for i in range(len(wight)):
path.append(wight[i])
self.backtracking(digits, index + 1, path, res) # 这里的index是独立集合的index
path.pop()
通过截图:
扩展写法:
资料:
视频讲解:https://www.bilibili.com/video/BV1yV4y1V7Ug
标签:digits,index,17,res,self,随想录,len,字母组合,path From: https://www.cnblogs.com/liqi175/p/17992291