- Preface
- FAQ
- Guidelines for Contributing
- Contributors
- Part I - Basics
- Basics Data Structure
- String
- Linked List
- Binary Tree
- Huffman Compression
- Queue
- Heap
- Stack
- Set
- Map
- Graph
- Basics Sorting
- 算法复习——排序
- Bubble Sort
- Selection Sort
- Insertion Sort
- Merge Sort
- Quick Sort
- Heap Sort
- Bucket Sort
- Counting Sort
- Radix Sort
- Basics Algorithm
- Divide and Conquer
- Binary Search
- Math
- Greatest Common Divisor
- Prime
- Knapsack
- Probability
- Shuffle
- Bitmap
- Basics Misc
- Bit Manipulation
- Part II - Coding
- String
- strStr
- Two Strings Are Anagrams
- Compare Strings
- Anagrams
- Longest Common Substring
- Rotate String
- Reverse Words in a String
- Valid Palindrome
- Longest Palindromic Substring
- Space Replacement
- Wildcard Matching
- Length of Last Word
- Count and Say
- Integer Array
- Remove Element
- Zero Sum Subarray
- Subarray Sum K
- Subarray Sum Closest
- Recover Rotated Sorted Array
- Product of Array Exclude Itself
- Partition Array
- First Missing Positive
- 2 Sum
- 3 Sum
- 3 Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Merge Sorted Array
- Merge Sorted Array II
- Median
- Partition Array by Odd and Even
- Kth Largest Element
- Binary Search
- Binary Search
- Search Insert Position
- Search for a Range
- First Bad Version
- Search a 2D Matrix
- Search a 2D Matrix II
- Find Peak Element
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array II
- Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array II
- Median of two Sorted Arrays
- Sqrt x
- Wood Cut
- Math and Bit Manipulation
- Single Number
- Single Number II
- Single Number III
- O1 Check Power of 2
- Convert Integer A to Integer B
- Factorial Trailing Zeroes
- Unique Binary Search Trees
- Update Bits
- Fast Power
- Hash Function
- Count 1 in Binary
- Fibonacci
- A plus B Problem
- Print Numbers by Recursion
- Majority Number
- Majority Number II
- Majority Number III
- Digit Counts
- Ugly Number
- Plus One
- Linked List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List II
- Remove Duplicates from Unsorted List
- Partition List
- Add Two Numbers
- Two Lists Sum Advanced
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle II
- Reverse Linked List
- Reverse Linked List II
- Merge Two Sorted Lists
- Merge k Sorted Lists
- Reorder List
- Copy List with Random Pointer
- Sort List
- Insertion Sort List
- Palindrome Linked List
- Delete Node in the Middle of Singly Linked List
- Rotate List
- Swap Nodes in Pairs
- Remove Linked List Elements
- Binary Tree
- Binary Tree Preorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Maximum Depth of Binary Tree
- Balanced Binary Tree
- Binary Tree Maximum Path Sum
- Lowest Common Ancestor
- Invert Binary Tree
- Diameter of a Binary Tree
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- Subtree
- Binary Tree Zigzag Level Order Traversal
- Binary Tree Serialization
- Binary Search Tree
- Insert Node in a Binary Search Tree
- Validate Binary Search Tree
- Search Range in Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Binary Search Tree Iterator
- Exhaustive Search
- Subsets
- Unique Subsets
- Permutations
- Unique Permutations
- Next Permutation
- Previous Permuation
- Permutation Index
- Permutation Index II
- Permutation Sequence
- Unique Binary Search Trees II
- Palindrome Partitioning
- Combinations
- Combination Sum
- Combination Sum II
- Minimum Depth of Binary Tree
- Word Search
- Dynamic Programming
- Triangle
- Backpack
- Backpack II
- Minimum Path Sum
- Unique Paths
- Unique Paths II
- Climbing Stairs
- Jump Game
- Word Break
- Longest Increasing Subsequence
- Follow up
- Palindrome Partitioning II
- Longest Common Subsequence
- Edit Distance
- Jump Game II
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Distinct Subsequences
- Interleaving String
- Maximum Subarray
- Maximum Subarray II
- Longest Increasing Continuous subsequence
- Longest Increasing Continuous subsequence II
- Maximal Square
- Graph
- Find the Connected Component in the Undirected Graph
- Route Between Two Nodes in Graph
- Topological Sorting
- Word Ladder
- Bipartial Graph Part I
- Data Structure
- Implement Queue by Two Stacks
- Min Stack
- Sliding Window Maximum
- Longest Words
- Heapify
- Problem Misc
- Nuts and Bolts Problem
- String to Integer
- Insert Interval
- Merge Intervals
- Minimum Subarray
- Matrix Zigzag Traversal
- Valid Sudoku
- Add Binary
- Reverse Integer
- Gray Code
- Find the Missing Number
- Minimum Window Substring
- Continuous Subarray Sum
- Continuous Subarray Sum II
- Longest Consecutive Sequence
- Part III - Contest
- Google APAC
- APAC 2015 Round B
- Problem A. Password Attacker
- APAC 2016 Round D
- Problem A. Dynamic Grid
- Microsoft
- Microsoft 2015 April
- Problem A. Magic Box
- Problem B. Professor Q's Software
- Problem C. Islands Travel
- Problem D. Recruitment
- Microsoft 2015 April 2
- Problem A. Lucky Substrings
- Problem B. Numeric Keypad
- Problem C. Spring Outing
- Microsoft 2015 September 2
- Problem A. Farthest Point
- Appendix I Interview and Resume
- Interview
- Resume
- 術語表
Jump Game II
Source
- lintcode: (117) Jump Game II
Given an array of non-negative integers,
you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2.
(Jump 1 step from index 0 to 1, then 3 steps to the last index.)
题解(自顶向下-动态规划)
首先来看看使用动态规划的解法,由于复杂度较高在 A 元素较多时会出现 TLE ,因为时间复杂度接近 O(n3)O(n^3)O(n3). 工作面试中给出动规的实现就挺好了。
- State: f[i] 从起点跳到这个位置最少需要多少步
- Function: f[i] = MIN(f[j]+1, j < i && j + A[j] >= i) 取出所有能从 j 到 i 中的最小值
- Initialization: f[0] = 0,即一个元素时不需移位即可到达
- Answer: f[n-1]
C++ Dynamic Programming
class Solution {
public:
/**
* @param A: A list of lists of integers
* @return: An integer
*/
int jump(vector<int> A) {
if (A.empty()) {
return -1;
}
const int N = A.size() - 1;
vector<int> steps(N, INT_MAX);
steps[0] = 0;
for (int i = 1; i != N + 1; ++i) {
for (int j = 0; j != i; ++j) {
if ((steps[j] != INT_MAX) && (j + A[j] >= i)) {
steps[i] = steps[j] + 1;
break;
}
}
}
return steps[N];
}
};
源码分析
状态转移方程为
if ((steps[j] != INT_MAX) && (j + A[j] >= i)) {
steps[i] = steps[j] + 1;
break;
}
其中 break 即体现了 MIN 操作,最开始满足条件的 j 即为最小步数。
题解(贪心法-自底向上)
使用动态规划解 Jump Game 的题复杂度均较高,这里可以使用贪心法达到线性级别的复杂度。
贪心法可以使用自底向上或者自顶向下,首先看看我最初使用自底向上做的。对 A 数组遍历,找到最小的下标 min_index
,并在下一轮中用此 min_index
替代上一次的 end
, 直至 min_index
为 0,返回最小跳数 jumps
。以下的实现有个 bug,细心的你能发现吗?
C++ greedy from bottom to top, bug version
class Solution {
public:
/**
* @param A: A list of lists of integers
* @return: An integer
*/
int jump(vector<int> A) {
if (A.empty()) {
return -1;
}
const int N = A.size() - 1;
int jumps = 0;
int last_index = N;
int min_index = N;
for (int i = N - 1; i >= 0; --i) {
if (i + A[i] >= last_index) {
min_index = i;
}
if (0 == min_index) {
return ++jumps;
}
if ((0 == i) && (min_index < last_index)) {
++jumps;
last_index = min_index;
i = last_index - 1;
}
}
return jumps;
}
};
源码分析
使用 jumps 记录最小跳数,last_index 记录离终点最远的坐标,min_index 记录此次遍历过程中找到的最小下标。
以上的 bug 在于当 min_index 为 1 时,i = 0, for 循环中仍有--i,因此退出循环,无法进入 if (0 == min_index)
语句,因此返回的结果会小 1 个。
C++ greedy, from bottom to top
class Solution {
public:
/**
* @param A: A list of lists of integers
* @return: An integer
*/
int jump(vector<int> A) {
if (A.empty()) {
return 0;
}
const int N = A.size() - 1;
int jumps = 0, end = N, min_index = N;
while (end > 0) {
for (int i = end - 1; i >= 0; --i) {
if (i + A[i] >= end) {
min_index = i;
}
}
if (min_index < end) {
++jumps;
end = min_index;
} else {
// cannot jump to the end
return -1;
}
}
return jumps;
}
};
源码分析
之前的 bug version 代码实在是太丑陋了,改写了个相对优雅的实现,加入了是否能到达终点的判断。在更新 min_index
的内循环中也可改为如下效率更高的方式:
for (int i = 0; i != end; ++i) {
if (i + A[i] >= end) {
min_index = i;
break;
}
}
题解(贪心法-自顶向下)
看过了自底向上的贪心法,我们再来瞅瞅自顶向下的实现。自顶向下使用 farthest
记录当前坐标出发能到达的最远坐标,遍历当前 start
与 end
之间的坐标,若 i+A[i] > farthest
时更新 farthest
(寻找最小跳数),当前循环遍历结束时递推 end = farthest
。 end >= A.size() - 1
时退出循环,返回最小跳数。
C++
/**
* http://www.jiuzhang.com/solutions/jump-game-ii/
*/
class Solution {
public:
/**
* @param A: A list of lists of integers
* @return: An integer
*/
int jump(vector<int> A) {
if (A.empty()) {
return 0;
}
const int N = A.size() - 1;
int start = 0, end = 0, jumps = 0;
while (end < N) {
int farthest = end;
for (int i = start; i <= end; ++i) {
if (i + A[i] >= farthest) {
farthest = i + A[i];
}
}
if (end < farthest) {
++jumps;
start = end + 1;
end = farthest;
} else {
// cannot jump to the end
return -1;
}
}
return jumps;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论