leetcode 17 电话号码的字母组合 18 四数之和
17. 电话号码的字母组合
难度中等1332收藏分享切换为英文接收动态反馈
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入:digits = ""
输出:[]
示例 3:
输入:digits = "2"
输出:["a","b","c"]
提示:
0 <= digits.length <= 4
digits[i]
是范围['2', '9']
的一个数字。
答案
from typing import List
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
d = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz"
}
i = len(digits) - 1
ans = []
while i >= 0:
arr = []
for j in d[digits[i]]:
if len(ans) > 0:
for i2 in ans:
arr.append(j+i2)
else:
arr.append(j)
i-=1
ans = arr
return ans
if __name__ == '__main__':
print(Solution().letterCombinations("345"))
18. 四数之和
难度中等858收藏分享切换为英文接收动态反馈
给定一个包含 n 个整数的数组 nums
和一个目标值 target
,判断 nums
中是否存在四个元素 *a,*b,c 和 d ,使得 a + b + c + d 的值与 target
相等?找出所有满足条件且不重复的四元组。
**注意:**答案中不可以包含重复的四元组。
示例 1:
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2:
输入:nums = [], target = 0
输出:[]
提示:
0 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 10
答案
#coding=utf-8
from typing import List
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
ans = []
nums.sort()
nlen = len(nums)
for i in range(nlen):
for j in range(i+1,nlen-1):
t = target - nums[i] - nums[j]
l = nlen - 1
for k in range(j+1,nlen):
while l > k and t < (nums[k] + nums[l]):
l -= 1
if l == k:
break
if (nums[k] + nums[l]) == t:
a = [nums[i],nums[j],nums[k],nums[l]]
if a not in ans:
ans.append(a)
return ans
def fourSum2(self, nums: List[int], target: int) -> List[List[int]]:
nlen = len(nums)
ans = []
if nlen < 4:
return ans
nums.sort()
for i in range(nlen - 3):
if i > 0 and nums[i] == nums[i-1]:
continue
if nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target:
break
if nums[i] + nums[nlen-3] + nums[nlen-2] + nums[nlen-1] < target:
continue
for j in range(i+1,nlen-2):
if j > i+1 and nums[j] == nums[j - 1]:
continue
if nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target:
break
if nums[i] + nums[j] + nums[nlen - 2] + nums[nlen - 1] < target:
continue
left,right = j + 1,nlen - 1
while right > left:
t = nums[i] + nums[j] + nums[left] + nums[right]
if t == target:
ans.append([nums[i], nums[j], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
right -= 1
elif t < target:
left += 1
else:
right -= 1
return ans
if __name__ == '__main__':
#[-2, -1, 0, 0, 1, 2]
nums = [2,2,2,2,2]
target = 8
print(Solution().fourSum(nums,target))