跳跃游戏||
来源:力扣(LeetCode) 链接:leetcode.cn/problems/ju…
给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。
每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说,如果你在 nums[i] 处,你可以跳转到任意 nums[i + j] 处:
- 0 <= j <= nums[i]
- i + j < n
返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]。
示例 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
- 题目保证可以到达 nums[n-1]
代码
class Solution {
public int jump(int[] nums) {
int n = nums.length;
int end = 0; // 当前能跳到的最远位置
int farthest = 0; // 下一步能跳到的最远位置
int jumps = 0; // 跳跃次数
for (int i = 0; i < n - 1; i++) {
farthest = Math.max(farthest, i + nums[i]); // 更新下一步能跳到的最远位置
if (i == end) { // 到达当前能跳到的最远位置
jumps++; // 进行一次跳跃
end = farthest; // 更新当前能跳到的最远位置
}
}
return jumps;
}
}
思路分析
- 初始化当前能跳到的最远位置
end为0,下一步能跳到的最远位置farthest为0,跳跃次数jumps为0。 - 遍历数组,对于每个位置
i,更新下一步能跳到的最远位置farthest,取当前位置能跳到的最远位置i + nums[i]和当前farthest的较大值。 - 当遍历到当前能跳到的最远位置
end时,说明必须进行一次跳跃,更新jumps加1,并将当前能跳到的最远位置end更新为下一步能跳到的最远位置farthest。 - 重复步骤2和步骤3,直到遍历完数组。
- 最终得到的
jumps即为跳跃到数组末尾所需的最小跳跃次数。
全排列
来源:力扣(LeetCode) 链接:leetcode.cn/problems/pe…
给定一个不含重复数字的数组 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 中的所有整数 互不相同
代码
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(nums, new ArrayList<>(), result);
return result;
}
private void backtrack(int[] nums, List<Integer> tempList, List<List<Integer>> result) {
if (tempList.size() == nums.length) {
result.add(new ArrayList<>(tempList));
} else {
for (int i = 0; i < nums.length; i++) {
if (tempList.contains(nums[i])) {
continue;
}
tempList.add(nums[i]);
backtrack(nums, tempList, result);
tempList.remove(tempList.size() - 1);
}
}
}
}
思路分析
- 创建一个结果列表
result来存储所有的全排列。 - 调用回溯函数
backtrack,传入初始数组nums、空的临时列表tempList以及结果列表result。 - 在回溯函数
backtrack中,当临时列表tempList的大小等于数组nums的长度时,说明已经生成了一个完整的全排列,将其加入结果列表result中。 - 否则,遍历数组
nums,对于每个元素,如果临时列表tempList已经包含了该元素,跳过继续下一个元素。否则,将该元素加入临时列表tempList中,然后递归调用回溯函数backtrack,生成下一个位置的全排列。 - 递归调用结束后,将临时列表
tempList的最后一个元素移除,以便进行下一轮的遍历。 - 最终,返回结果列表
result,其中存储了所有的全排列。