LeetCode 中等題解(4)

40 組合總和 II

Question

給定一個數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和爲 target 的組合。

candidates 中的每個數字在每個組合中只能使用一次。

說明:

  • 所有數字(包括目標數)都是正整數。
  • 解集不能包含重複的組合。

示例 1:

輸入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集爲:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

示例 2:

輸入: candidates = [2,5,2,1,2], target = 5,
所求解集爲:
[
  [1,2,2],
  [5]
]

Answer

#
# @lc app=leetcode.cn id=40 lang=python3
#
# [40] 組合總和 II
#


# @lc code=start
class Solution:
    def combinationSum2(self, candidates: List[int],
                        target: int) -> List[List[int]]:
        if (not candidates):
            return []
        n = len(candidates)
        candidates.sort()
        res = []

        def helper(i, tmp, target):
            if (target == 0):
                res.append(tmp)
                return
            if (i == n or target < candidates[i]):
                return
            for j in range(i, n):
                if (j > i and candidates[j] == candidates[j - 1]):
                    continue
                helper(j + 1, tmp + [candidates[j]], target - candidates[j])

        helper(0, [], target)
        return res


# @lc code=end

43 字符串相乘

Question

給定兩個以字符串形式表示的非負整數 num1num2,返回 num1num2 的乘積,它們的乘積也表示爲字符串形式。

示例 1:

輸入: num1 = "2", num2 = "3"
輸出: "6"

示例 2:

輸入: num1 = "123", num2 = "456"
輸出: "56088"

說明:

  1. num1num2 的長度小於110。
  2. num1num2 只包含數字 0-9
  3. num1num2 均不以零開頭,除非是數字 0 本身。
  4. 不能使用任何標準庫的大數類型(比如 BigInteger)直接將輸入轉換爲整數來處理

Answer

#
# @lc app=leetcode.cn id=43 lang=python3
#
# [43] 字符串相乘
#


# @lc code=start
class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        if num1 == "0" or num2 == "0":
            return "0"
        nums1_list = [int(i) for i in num1]
        nums2_list = [int(i) for i in num2]

        result_sum = [0]

        for i in range(1, len(nums1_list) + 1):
            _result = [nums1_list[-i] * x for x in nums2_list]

            d = 0
            for j in range(1, len(_result) + 1):
                if (_result[-j] + d) // 10 > 0:
                    _d = d
                    d = (_result[-j] + d) // 10
                    _result[-j] = (_result[-j] + _d) % 10
                else:
                    _result[-j] += d
                    d = 0
            if d > 0:
                _result.insert(0, d)

            for j in range(i - 1):
                _result.append(0)

            result = _result if len(_result) > len(result_sum) else result_sum

            length = min(len(_result), len(result_sum))
            for j in range(1, length + 1):
                result[-j] = result_sum[-j] + _result[-j]
            result_sum = result

        d = 0
        for i in range(1, len(result_sum) + 1):
            if (result_sum[-i] + d) // 10 > 0:
                _d = d
                d = (result_sum[-i] + d) // 10
                result_sum[-i] = (result_sum[-i] + _d) % 10
            else:
                result_sum[-i] += d
                d = 0
        if d > 0:
            result_sum.insert(0, d)

        result_str = ""
        for i in range(len(result_sum)):
            result_str += str(result_sum[i])

        return result_str


# @lc code=end

46 全排列

Question

給定一個 沒有重複 數字的序列,返回其所有可能的全排列。

示例:

輸入: [1,2,3]
輸出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

Answer

#
# @lc app=leetcode.cn id=46 lang=python3
#
# [46] 全排列
#


# @lc code=start
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        result = []

        def perm(res_nums, cur_result):
            if len(res_nums) == 1:
                result.append(cur_result + res_nums)
                return
            for i in range(len(res_nums)):
                perm(res_nums[:i]+res_nums[i+1:], cur_result + [res_nums[i]])

        perm(nums, [])

        return result


# @lc code=end

47 全排列 II

Question

給定一個可包含重複數字的序列,返回所有不重複的全排列。

示例:

輸入: [1,1,2]
輸出:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

Answer

#
# @lc app=leetcode.cn id=47 lang=python3
#
# [47] 全排列 II
#


# @lc code=start
class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        result = []
        nums.sort()

        def perm(res_nums, cur_result):
            if len(res_nums) == 1:
                result.append(cur_result + res_nums)
                return
            for i in range(len(res_nums)):
                if i < len(res_nums) - 1 and res_nums[i] == res_nums[i + 1]:
                    continue
                perm(res_nums[:i] + res_nums[i + 1:],
                     cur_result + [res_nums[i]])

        perm(nums, [])

        return result


# @lc code=end

48 旋轉圖像

Question

給定一個 n × n 的二維矩陣表示一個圖像。

將圖像順時針旋轉 90 度。

說明:

你必須在原地旋轉圖像,這意味着你需要直接修改輸入的二維矩陣。請不要使用另一個矩陣來旋轉圖像。

示例 1:

給定 matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

原地旋轉輸入矩陣,使其變爲:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

示例 2:

給定 matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

原地旋轉輸入矩陣,使其變爲:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

Answer

#
# @lc app=leetcode.cn id=48 lang=python3
#
# [48] 旋轉圖像
#


# @lc code=start
class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix)
        for i in range(n):
            for j in range(i, n):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
        for i in matrix:
            i.reverse()

# @lc code=end

49 字母異位詞分組

Question

給定一個字符串數組,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字符串。

示例:

輸入: ["eat", "tea", "tan", "ate", "nat", "bat"],
輸出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

說明:

  • 所有輸入均爲小寫字母。
  • 不考慮答案輸出的順序。

Answer

#
# @lc app=leetcode.cn id=49 lang=python3
#
# [49] 字母異位詞分組
#


# @lc code=start
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        result = {}
        for str_i in strs:
            _ = sorted(str_i)
            strs_key = ""
            for i in _:
                strs_key += i

            if strs_key not in result.keys():
                result[strs_key] = [str_i]
            else:
                result[strs_key].append(str_i)
        total_result = []
        for key in result.keys():
            total_result.append(result[key])
        return total_result


# @lc code=end

50 Pow(x, n)

Question

實現 pow(x, n) ,即計算 x 的 n 次冪函數。

示例 1:

輸入: 2.00000, 10
輸出: 1024.00000

示例 2:

輸入: 2.10000, 3
輸出: 9.26100

示例 3:

輸入: 2.00000, -2
輸出: 0.25000
解釋: 2-2 = 1/22 = 1/4 = 0.25

說明:

  • -100.0 < x < 100.0
  • n 是 32 位有符號整數,其數值範圍是 [−231, 231 − 1] 。

Answer

#
# @lc app=leetcode.cn id=50 lang=python3
#
# [50] Pow(x, n)
#


# @lc code=start
class Solution:
    def myPow(self, x: float, n: int) -> float:
        judge = True
        if n < 0:
            n = -n
            judge = False
        final = 1
        while n > 0:
            if n & 1:  #代表是奇數
                final *= x
            x *= x
            n >>= 1  # 右移一位
        return final if judge else 1 / final


# @lc code=end

54 螺旋矩陣

Question

給定一個包含 m x n 個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。

示例 1:

輸入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
輸出: [1,2,3,6,9,8,7,4,5]

示例 2:

輸入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
輸出: [1,2,3,4,8,12,11,10,9,5,6,7]

Answer

#
# @lc app=leetcode.cn id=54 lang=python3
#
# [54] 螺旋矩陣
#


# @lc code=start
class Solution:
    # def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
    def spiralOrder(self, matrix):
        result = []
        if matrix == []:
            return result
        m, n = len(matrix), len(matrix[0])
        state = [[0 for _ in range(n)] for _ in range(m)]
        i, j = 0, 0
        result.append(matrix[i][j])
        state[i][j] = 1
        count = m * n - 1
        while (count):
            while (j < n - 1 and state[i][j + 1] == 0):
                j += 1
                result.append(matrix[i][j])
                state[i][j] = 1
                count -= 1
            while (i < m - 1 and state[i + 1][j] == 0):
                i += 1
                result.append(matrix[i][j])
                state[i][j] = 1
                count -= 1
            while (j > 0 and state[i][j - 1] == 0):
                j -= 1
                result.append(matrix[i][j])
                state[i][j] = 1
                count -= 1
            while (i > 0 and state[i - 1][j] == 0):
                i -= 1
                result.append(matrix[i][j])
                state[i][j] = 1
                count -= 1
        return result


# @lc code=end

55 跳躍遊戲

Question

給定一個非負整數數組,你最初位於數組的第一個位置。

數組中的每個元素代表你在該位置可以跳躍的最大長度。

判斷你是否能夠到達最後一個位置。

示例 1:

輸入: [2,3,1,1,4]
輸出: true
解釋: 我們可以先跳 1 步,從位置 0 到達 位置 1, 然後再從位置 1 跳 3 步到達最後一個位置。

示例 2:

輸入: [3,2,1,0,4]
輸出: false
解釋: 無論怎樣,你總會到達索引爲 3 的位置。但該位置的最大跳躍長度是 0 , 所以你永遠不可能到達最後一個位置。

Answer

#
# @lc app=leetcode.cn id=55 lang=python3
#
# [55] 跳躍遊戲
#


# @lc code=start
class Solution:
    # def canJump(self, nums: List[int]) -> bool:
    def canJump(self, nums):
        nums_len = len(nums)
        state = [0 for _ in range(nums_len)]
        state[-1] = 1

        if nums_len == 1:
            return True

        i = nums_len - 2
        while (i != -1):
            max_pos = min(i + 1 + nums[i], nums_len)
            if 1 in state[i + 1:max_pos]:
                state[i] = 1
            i -= 1

        if state[0] == 0:
            return False
        else:
            return True

# @lc code=end

56 合併區間

Question

給出一個區間的集合,請合併所有重疊的區間。

示例 1:

輸入: [[1,3],[2,6],[8,10],[15,18]]
輸出: [[1,6],[8,10],[15,18]]
解釋: 區間 [1,3] 和 [2,6] 重疊, 將它們合併爲 [1,6].

示例 2:

輸入: [[1,4],[4,5]]
輸出: [[1,5]]
解釋: 區間 [1,4] 和 [4,5] 可被視爲重疊區間。

Answer

#
# @lc app=leetcode.cn id=56 lang=python3
#
# [56] 合併區間
#


# @lc code=start
class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        intervals = sorted(intervals)
        p = 1
        while (p < len(intervals)):
            if intervals[p][0] >= intervals[
                    p - 1][0] and intervals[p][0] <= intervals[p - 1][1]:
                if intervals[p][1] <= intervals[p - 1][1]:
                    intervals.remove(intervals[p])
                else:
                    intervals[p - 1] = [intervals[p - 1][0], intervals[p][1]]
                    intervals.remove(intervals[p])
            else:
                p += 1
        return intervals


# @lc code=end

59 螺旋矩陣 II

Question

給定一個正整數 n,生成一個包含 1 到 n2 所有元素,且元素按順時針順序螺旋排列的正方形矩陣。

示例:

輸入: 3
輸出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

Answer

#
# @lc app=leetcode.cn id=59 lang=python3
#
# [59] 螺旋矩陣 II
#


# @lc code=start
class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        state = [[0 for _ in range(n)] for _ in range(n)]
        i, j = 0, 0
        state[i][j] = 1
        count = n**2 - 1
        while (count):
            while (j < n - 1 and state[i][j + 1] == 0):
                j += 1
                state[i][j] = n**2 - count + 1
                count -= 1
            while (i < n - 1 and state[i + 1][j] == 0):
                i += 1
                state[i][j] = n**2 - count + 1
                count -= 1
            while (j > 0 and state[i][j - 1] == 0):
                j -= 1
                state[i][j] = n**2 - count + 1
                count -= 1
            while (i > 0 and state[i - 1][j] == 0):
                i -= 1
                state[i][j] = n**2 - count + 1
                count -= 1
        return state


# @lc code=end

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章