2021年5月22日

15 . 三数之和

给定包含n个整数的数组nums, 找出所有和为0且不重复的三元组。

class Solution:
	def threeSum(self, nums: Lis[int]) -> List[List[int]]:
		n = len(nums)
		nums.sort()
		ans = list()
		#枚举
		for first in range(n):
			if first > 0 and nums[first] == nums[first - 1]:
				continue
			third = n - 1
			target -= nums[first]
			for second in range(first + 1, n):
				if second > first + 1 and nums[second] == nums[second - 1]:
					continue
				while second < third and nums[second] + nums[third] > target:
					third -= 1
				if second == third:
					break
				 if (nums[second] + nums[third] == target) {
                    ans.push_back({nums[first], nums[second], nums[third]});
                }
     			  if nums[second] + nums[third] == target:
                    ans.append([nums[first], nums[second], nums[third]])
        		return ans

时间复杂度:O(N^2)
空间复杂度:O(NlogN)

16 . 最接近的三数之和

pass

17 . 电话号码中的字母

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

回溯法:

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return list()
        
        phoneMap = {
            "2": "abc",
            "3": "def",
            "4": "ghi",
            "5": "jkl",
            "6": "mno",
            "7": "pqrs",
            "8": "tuv",
            "9": "wxyz",
        }

        def backtrack(index: int):
            if index == len(digits):
                combinations.append("".join(combination))
            else:
                digit = digits[index]
                for letter in phoneMap[digit]:
                    combination.append(letter)
                    backtrack(index + 1)
                    combination.pop()

        combination = list()
        combinations = list()
        backtrack(0)
        return combinations
posted @ 2021-05-22 11:59  tianle1998  阅读(74)  评论(0)    收藏  举报