DataWhale编程——递归
Posted chanwunsam
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DataWhale编程——递归相关的知识,希望对你有一定的参考价值。
刚考完试的人没资格做代码分析。hhh其实是时间太赶了,就看了下题,思路还不是很清晰,第一题还算是自己做的,第二题就只能看答案了。
leetcode 017
代码实现
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
mapping = {‘2‘: ‘abc‘, ‘3‘: ‘def‘, ‘4‘: ‘ghi‘, ‘5‘: ‘jkl‘,
‘6‘: ‘mno‘, ‘7‘: ‘pqrs‘, ‘8‘: ‘tuv‘, ‘9‘: ‘wxyz‘}
if len(digits) == 0:
return []
if len(digits) == 1:
return list(mapping[digits[0]])
prev = self.letterCombinations(digits[:-1])
additional = mapping[digits[-1]]
return [s + c for s in prev for c in additional]
leetcode 046
代码实现
class Solution:
def dfs(self, nums, path, res):
"""
:type nums: List[int]
:type path: int
:type res: List[List[int]]
"""
if not nums:
res.append(path)
# return # backtracking
for i in range(len(nums)):
self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.dfs(nums, [], res)
return res
以上是关于DataWhale编程——递归的主要内容,如果未能解决你的问题,请参考以下文章