跳跃游戏 II
题目
给你一个非负整数数组 nums ,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
假设你总是可以到达数组的最后一个位置。
示例
输入: nums = [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
输入: nums = [2,3,0,1,4]
输出: 2
代码
class Solution(object):
def jump(self, nums):
if len(nums) == 1: return 0
ans = 0 #表示最远到达的位置
curDistance = 0 # 参数初始化简化写法
nextDistance = 0
for i in range(len(nums)): #遍历nums中的每个位置
nextDistance = max(i + nums[i], nextDistance) # 下一个跳跃位置
if i == curDistance:
if curDistance != len(nums) - 1:
ans += 1
curDistance = nextDistance
if nextDistance >= len(nums) - 1: break
return ans
组合求和 II
题目
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
说明:
所有数字(包括target)都是正整数
解集不能包括重复的组合
示例
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]
代码
class Solution(object):
def combinationSum2(self, candidates, target): #组合求和
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
path = []
def backtrack(candidates,target,sum,startIndex):
if sum == target: res.append(path[:])
for i in range(startIndex,len(candidates)): #要对同一数层使用过的元素进行跳过
if sum + candidates[i] > target: return
if i > startIndex and candidates[i] == candidates[i-1]: continue #直接用startIndex来去重,要对同一树层使用过得元素进行跳过
sum += candidates[i]
path.append(candidates[i])
backtrack(candidates,target,sum,i+1) # i+1 每个数字在每个组合中只能使用一次
sum -= candidates[i] #回溯法
path.pop()
candidates = sorted(candidates) #进行排序
backtrack(candidates,target,0,0)
return res