leetcode 45. 跳跃游戏 II 46. 全排列
45. 跳跃游戏 II
难度中等1273收藏分享切换为英文接收动态反馈
给你一个非负整数数组 nums
,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
假设你总是可以到达数组的最后一个位置。
示例 1:
输入: nums = [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
示例 2:
输入: nums = [2,3,0,1,4]
输出: 2
提示:
1 <= nums.length <= 104
0 <= nums[i] <= 1000
class Solution:
def jump(self, nums: List[int]) -> int:
length = len(nums) - 1
n = 0
ans = 0
if length == 0:
return 0
while n < length:
if n + nums[n] >= length:
ans += 1
break
step = (n + nums[n] + nums[n + nums[n]], n + nums[n])
for i in range(n + 1, n + nums[n] + 1):
step = max(step, (i + nums[i], i))
ans += 1
n = step[1]
return ans
def jump2(self, nums: List[int]) -> int:
length = len(nums)
ans = [length + 1 for _ in range(length)]
ans[0] = 0
for i in range(length):
for j in range(nums[i]):
if i + 1 + j < length:
ans[i + 1 + j] = min(ans[i] + 1, ans[i + 1 + j])
else:
break
return ans[-1]
def jump3(self, nums: List[int]) -> int:
n = len(nums)
maxPos, end, step = 0, 0, 0
for i in range(n - 1):
if maxPos >= i:
maxPos = max(maxPos, i + nums[i])
if i == end:
end = maxPos
step += 1
return step
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
nums = [2,3,1,1,4]
nums = [0]
nums = [1,3,1,3,1,1,1,1]
nums = [2, 3, 1, 1, 4]
nums = [2,3,0,1,4]
nums = [5,4,0,1,3,6,8,0,9,4,9,1,8,7,4,8]
nums = [1,2]
nums = [2, 3, 1, 1, 4]
# nums = [5,9,3,2,1,0,2,3,3,1,0,0]
# nums = [1,2,3]
# nums = [6,9,1,5,6,0,0,5,9]
# nums = [9,4,5,4,1,8,1,2,0,7,8,7,0,6,6,1,1,2,5,0,9,8,4,7,9,6,8,1,4,0,8,5,5,3,9,8,1,2,2,3,0,1,3,2,7,9,3,0,1]
# nums = [1,1,1,1]
nums = [2,3,1]
nums = [2, 3, 1, 1, 4, 1, 2, 3]
a = (1,3)
b = (2,1)
# print(max(a,b))
print(Solution().jump2(nums))
46. 全排列
难度中等1637收藏分享切换为英文接收动态反馈
给定一个不含重复数字的数组 nums
,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例 1:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
示例 2:
输入:nums = [0,1]
输出:[[0,1],[1,0]]
示例 3:
输入:nums = [1]
输出:[[1]]
提示:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
nums
中的所有整数 互不相同
通过次数452,517
提交次数577,452
# leetcode submit region begin(Prohibit modification and deletion)
from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def dfs(nums: List[int]):
arr = []
if len(nums) == 2:
return [[nums[0], nums[1]], [nums[1], nums[0]]]
for i in range(len(nums)):
nums2 = nums.copy()
del nums2[i]
r = dfs(nums2)
for k in r:
k.insert(0, nums[i])
arr.append(k)
return arr
if len(nums) < 2:
return [nums]
return dfs(nums)
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
nums = [1, 2, 3]
print(Solution().permute(nums))