方法上和昨天是一样的,都是想办法用回溯替代for循环
17. Letter Combinations of a Phone Number
这道题基本思路就是用一个指针来顺序指向每一位,然后进行回溯
Way1:
产生一个数字和字母的hash map,然后再回溯过程中,每次对数字对应的字母进行循环然后回溯
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
res=[]
path=""
dic={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
def combine(k,digits,path):
if k==len(digits):
res.append(path)
return
for ch in dic[digits[k]]:
path+=ch
combine(k+1,digits,path)
path=path[:-1]
combine(0,digits,path)
if not digits:
return []
return res
216. Combination Sum III
这道题相对于上一题更加简单,直接用回溯替代for循环即可
Way1:
每加一次k就减1并且n要减i
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res=[]
path=[]
def combine(k,n,start):
if n<0:
return
if n==0 and k==0:
res.append(path[:])
return
for i in range(start,10):
path.append(i)
combine(k-1,n-i,i+1)
path.pop()
combine(k,n,1)
return res