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 {
private 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) {
Set<String> visited = new HashSet<String>();
String begin = 0 + "/" + 1;
visited.add(begin);
Queue<Node> queue = new LinkedList<Node>();
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;
}
String s1 = (node.pos + node.speed) + "/" + (node.speed * 2);
String s2 = (node.pos + "/" + (node.speed > 0 ? -1 : 1));
// 如果speed是正數;
// node.pos + node.speed = target;
// node.pos + node.speed + target = 2 * target;
// node.pos + node.speed < 2* target;
if(Math.abs(node.pos + node.speed) < 2 * target && !visited.contains(s1)) {
queue.offer(new Node(node.pos + node.speed, node.speed * 2));
visited.add(s1);
}
// 如果speed是負數;
// node.pos + node.speed = target;
// target 是正數,所以Math.abs(node.speed) < target
// node.pos - Math.abs(node.speed) = target;
// node.pos - target < target;
if(Math.abs(node.pos - target) < target && !visited.contains(s2)) {
queue.offer(new Node(node.pos, node.speed > 0 ? -1 : 1));
visited.add(s2);
}
}
step++;
}
return -1;
}
}