问两道leetcode上的jump game 题# JobHunting - 待字闺中
f*m
1 楼
(1)Jump Game:
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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
不知道我下面的解法对不对?用了DP,用f存储以前的计算结果。
bool jump(vector& A, int n, vector f){
if (n == 0){
f[0] = true;
return true;
}
if (f[n] != -1)
return f[n];
bool temp = false;
for (int i = 0; i < n; i++){
if (n-i <= A[i])
temp = temp || jump(A, i, f);
}
f[n] = temp;
return f[n];
}
(2) Jump game 2:
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.
For 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.)
我的做法:
int minjump(vector& a, int n, vector& f){
if (n == 0){
f[n] = 0;
return f[n];
}
if (f[n] != -1)
return f[n];
int minj = INT_MAX;
for (int i = 0; i < n; i++){
if (n-i <= a[i]){
if (minjump(a, i, f)+1 < minj)
minj = minjump(a, i, f)+1;
}
}
f[n] = minj;
return f[n];
}
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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
不知道我下面的解法对不对?用了DP,用f存储以前的计算结果。
bool jump(vector
if (n == 0){
f[0] = true;
return true;
}
if (f[n] != -1)
return f[n];
bool temp = false;
for (int i = 0; i < n; i++){
if (n-i <= A[i])
temp = temp || jump(A, i, f);
}
f[n] = temp;
return f[n];
}
(2) Jump game 2:
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.
For 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.)
我的做法:
int minjump(vector
if (n == 0){
f[n] = 0;
return f[n];
}
if (f[n] != -1)
return f[n];
int minj = INT_MAX;
for (int i = 0; i < n; i++){
if (n-i <= a[i]){
if (minjump(a, i, f)+1 < minj)
minj = minjump(a, i, f)+1;
}
}
f[n] = minj;
return f[n];
}