本文主要是介绍Leetcode 17与46,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Leetcode 17
- 题目描述:
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"].
- 思路代码:
class Solution:def letterCombinations(self, digits):""":type digits: str:rtype: List[str]"""m = ["0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]if len(digits) == 0:return []if len(digits) == 1:return list(m[int(digits)])prev = self.letterCombinations(digits[:-1])p = list(m[int(digits[-1])])return [s+c for s in prev for c in p]
Leetcode 46
- 题目描述:
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]
]
- 思路代码:
class Solution:def permute(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""perms = [[]] for n in nums:new_perms = []for perm in perms:for i in range(len(perm)+1): new_perms.append(perm[:i] + [n] + perm[i:]) ###insert nperms = new_permsreturn perms
这篇关于Leetcode 17与46的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!