Description
Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions ‘A’ (accelerate) and ‘R’ (reverse):
When you get an instruction ‘A’, your car does the following:
position += speed
speed *= 2
When you get an instruction ‘R’, your car does the following:
If your speed is positive then speed = -1
otherwise speed = 1
Your position stays the same.
For example, after commands “AAR”, your car goes to positions 0 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1.
Given a target position target, return the length of the shortest sequence of instructions to get there.
Examples
Example 1:
Input: target = 3
Output: 2
Explanation:
The shortest instruction sequence is “AA”.
Your position goes from 0 --> 1 --> 3.
Example 2:
Input: target = 6
Output: 5
Explanation:
The shortest instruction sequence is “AAARA”.
Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.
Constraints:
1 <= target <= 1 0 4 10^4 104
思路
难以想象最后的代码只有这么短
- 其实最开始的时候我想的很简单,对需要到达target的car来说,有两种到达方式,假设存在一个正整数
n
n
n,使得
2
n
−
1
−
1
<
t
a
r
g
e
t
<
2
n
−
1
2^{n-1} - 1 < target < 2^n - 1
2n−1−1<target<2n−1
- 第一种是慢慢往前蛄蛹,可以理解为先到达 2 n − 1 − 1 2^{n-1} - 1 2n−1−1 ,然后掉头两次,再走 t a r g e t − 2 n − 1 target - 2^{n-1} target−2n−1的路
- 第二种是直接超车,到达 2 n − 1 2^n - 1 2n−1,再掉头,走 2 n − 1 − t a r g e t 2^n - 1- target 2n−1−target的路
- 在这种情况下,我设计的更新函数就是 dp[target] = Math.min(racecar(target - Math.pow(2, n - 1) + 1) + 2, racecar(Math.pow(2, n) - 1 - target) + n
- 但这样会有一个问题,比如对于target=5来说,他可以选择往回走1332235,就是可以从3→2,这点在我的第一种想法里没有考虑到
所以改进一下想法
- 依旧对于到达target的car来说,有两种到达方式,假设存在一个正整数
n
n
n,使得
2
n
−
1
−
1
<
t
a
r
g
e
t
<
2
n
−
1
2^{n-1} - 1 < target < 2^n - 1
2n−1−1<target<2n−1
- 第一种与上面类似,到达 2 n − 1 2^n - 1 2n−1,再掉头,走 2 n − 1 − t a r g e t 2^n - 1- target 2n−1−target的路
- 第二种在到达了 2 n − 1 − 1 2^{n-1} - 1 2n−1−1 后,出现了不同,他先掉头,然后吨吨吨走 m m m次A,再从 2 n − 1 − 1 − ( 2 m − 1 ) = 2 n − 1 − 2 m 2^{n-1} - 1 - (2^m - 1) = 2^{n-1}-2^m 2n−1−1−(2m−1)=2n−1−2m的位置开始往target方向走
- 根据上面的情况,更新函数为dp[target] = racecar(Math.pow(2, n) - 1 - target) + 1 + n; dp[target] = Math.min(dp[target], racecar(target - Math.pow(2, n - 1) + Math.pow(m)) + m + n + 1) for m = 0~(n - 1)
代码
class Solution {
int[] dp = new int[10001];
public int racecar(int target) {
if (dp[target] > 0)
return dp[target];
int stopped = (int)(Math.log(target) / Math.log(2)) + 1;
int stopped_pos = (int)Math.pow(2, stopped) - 1;
if (stopped_pos == target){
dp[target] = stopped;
return stopped;
}
dp[target] = racecar(stopped_pos - target) + 1 + stopped;
for (int i = 0; i < stopped - 1; i++){
int curr = target - (int)Math.pow(2, stopped - 1) + (int)Math.pow(2, i);
dp[target] = Math.min(dp[target], racecar(curr) + stopped + i + 1);
}
return dp[target];
}
}