Study Plan For Algorithms - Part9

WindMay發表於2024-08-23

1. 電話號碼的字母組合
題目連結:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/
給定一個僅包含數字 2-9 的字串,返回所有它能表示的字母組合。

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

        def backtrack(index, cur_str):
            if index == len(digits):
                res.append(cur_str)
                return
            digit = digits[index]
            letters = mapping[digit]
            for letter in letters:
                backtrack(index + 1, cur_str + letter)

        backtrack(0, '')
        return res

2. 四數之和
題目連結:https://leetcode.cn/problems/4sum/
給定一個由 n 個整陣列成的陣列 nums ,和一個目標值 target 。請找出並返回滿足下述全部條件且不重複的四元組 [nums[a], nums[b], nums[c], nums[d]] (若兩個四元組元素一一對應,則認為兩個四元組重複):

  • 0 <= a, b, c, d < n
  • a、b、c 和 d 互不相同
  • nums[a] + nums[b] + nums[c] + nums[d] == target
class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        res = []
        n = len(nums)

        for i in range(n - 3):
            if i > 0 and nums[i] == nums[i - 1]: 
                continue
            for j in range(i + 1, n - 2):
                if j > i + 1 and nums[j] == nums[j - 1]: 
                    continue
                left = j + 1
                right = n - 1
                while left < right:
                    total = nums[i] + nums[j] + nums[left] + nums[right]
                    if total == target:
                        res.append([nums[i], nums[j], nums[left], nums[right]])
                        while left < right and nums[left] == nums[left + 1]: 
                            left += 1
                        while left < right and nums[right] == nums[right - 1]:  
                            right -= 1
                        left += 1
                        right -= 1
                    elif total < target:
                        left += 1
                    else:
                        right -= 1
        return res        

相關文章