- Letter Combinations of a Phone Number
题目
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
思路
字符串集合不断作笛卡尔积。
例如:求“23”时,先放digits中的第一位“2”,就是[“a”,“b”,“c”]了,然后是digits中的下一位3,再将[“a”,“b”,“c”]与剩余数字串“3”对应的字符列表[“d”,“e”,“f”]做笛卡尔积,于是就得到了[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]。
class Solution(object):
def addDigit(self,digit,ans):
tmp = []
for element in digit:
if len(ans) == 0:
tmp.append(element)
for s in ans:
tmp.append(s + element)
return tmp
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
ans = []
dic = {'0':'','1':'*','2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
for element in digits:
ans = self.addDigit(dic[element],ans)
return ans
46. Permutations
题目
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路
一个数的全排列是其本身,然后再其余的一组,不断变换位置
for里a的输出,
[1, 2]
[1]
[1, 3]
[1]
[]
[2, 1]
[2]
[2, 3]
[2]
[]
[3, 1]
[3]
[3, 2]
[3]
[]
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res=[]
def perm(res,a,num,n,max):
if n==max:
res.append(a)
for i in range(0,len(num)):
perm(res,a+[num[i]],num[:i]+num[i+1:],n+1,max)
perm(res,[],nums,0,len(nums))
return res