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.
Now for some target position, say the length of the shortest sequence of instructions to get there.
Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3.
思路:这题面试的时候,只能够相出BFS,我觉得也可以了。因为求最小的步骤,就是BFS擅长的。下一层只能有两个状态: A, R
node.pos + node.speed, speed * 2;也就是每个node的状态分两个维度,一个是pos,一个是速度;
那么要么加速,要么反转,反转的话无论什么speed,都是反向,速度变成1或者-1;
那么用BFS来做,就用string来表示状态,然后做level order traverse;注意这题要剪枝,否则TLE
如果speed是正数: 下一层pos + speed = target, 那么 pos + speed + target = 2*target, 那么pos + speed < 2*target;
如果speed是负数,下一层pos + speed = target, 那么Math.abs(speed) < target, 那么也就是pos - Math.abs(speed) = target.
pos - target < target; O(2 ^ step);
class Solution {
public class Node {
public int pos;
public int speed;
public Node(int pos, int speed) {
this.pos = pos;
this.speed = speed;
}
}
public int racecar(int target) {
HashSet<String> visited = new HashSet<>();
visited.add(0 + ":" + "1");
Queue<Node> queue = new LinkedList<>();
queue.offer(new Node(0, 1));
int step = 0;
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
Node node = queue.poll();
if(node.pos == target) {
return step;
}
// two cases:
// A
String s1 = node.pos + node.speed + ":" + node.speed * 2;
// node.pos + node.speed = target;
// node.pos + node.speed + target = 2 * target;
// node.pos + node.speed < 2 * target;
if(!visited.contains(s1) && node.pos + node.speed < 2 * target) {
queue.offer(new Node(node.pos + node.speed, node.speed * 2));
visited.add(s1);
}
// R
String s2 = node.pos + ":" + (node.speed > 0 ? -1 : 1);
// node.pos - node.speed = target;
// 如果只有一步到达target,那么speed必须小于target
// Math.abs(node.speed) < target;
// Math.abs(node.speed) - target < 0 < target;
if(!visited.contains(s2) && Math.abs(node.speed) - target < target) {
queue.offer(new Node(node.pos, (node.speed > 0 ? -1 : 1)));
visited.add(s2);
}
}
step++;
}
return -1;
}
}