Letter Combinations of a Phone Number
这题iterate方法的基本思路就是连续做+1,+1的含义就是移动同一数字对应字母下一个index处。算法是两层循环,外层是每一个输出,内层是一个数的每一位。难点是循环的invariant:外层是carry!=1,因为如果内层循环最高位仍有进位说明已经过了最后一个对应string。内层从低到高遍历每一位,但如果carry变为0,要break中止。
错误点
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
def getOneRes(indices):
res = []
for i in range(len(indices)):
res.append(dmap[ord(digits[i])-ord('0')][indices[i]])
return ''.join(res)
if not digits: return []
dmap = ["", "", "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
indices = [0]*len(digits)
carry = 0
res = []
while not carry:
res.append(getOneRes(indices))
for i in range(len(digits)-1, -1, -1):
indices[i] += 1
if indices[i]==len(dmap[ord(digits[i])-ord('0')]):
indices[i]=0
carry=1
else:
carry=0
break
return res