LeetCode 818. Race Car
原题链接在这里:https://leetcode.com/problems/race-car/
题目:
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.
Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.
Note:
1 <= target <= 10000
.
题解:
Use BFS to find out shortest sequence.
Each step, there are 2 possibilities, either A or R. Maintain a set to store visited state.
If current position is alrady beyond 2 * target, it can't make shortest path.
Time Complexity: O(nlogn). n = target. totoally there are 2*n positions, each position could be visited 2*logn times at most. Since the speed could not be beyond logn.
Space: O(n).
AC Java:
1 class Solution { 2 public int racecar(int target) { 3 if(target == 0){ 4 return 0; 5 } 6 7 int step = 0; 8 LinkedList<int []> que = new LinkedList<>(); 9 que.add(new int[]{0, 1}); 10 int curCount = 1; 11 int nextCount = 0; 12 13 HashSet<String> visited = new HashSet<>(); 14 visited.add(0 + "," + 1); 15 16 while(!que.isEmpty()){ 17 int [] cur = que.poll(); 18 curCount--; 19 20 if(cur[0] == target){ 21 return step; 22 } 23 24 int [] next1 = new int[]{cur[0]+cur[1], 2*cur[1]}; 25 int [] next2 = new int[]{cur[0], cur[1] > 0 ? -1 : 1}; 26 if(0<next1[0] && next1[0]<=target*2 && !visited.contains(next1[0] + "," + next1[1])){ 27 que.add(next1); 28 visited.add(next1[0] + "," + next1[1]); 29 nextCount++; 30 } 31 32 if(!visited.contains(next2[0] + "," + next2[1])){ 33 que.add(next2); 34 visited.add(next2[0] + "," + next2[1]); 35 nextCount++; 36 } 37 38 if(curCount == 0){ 39 curCount = nextCount; 40 nextCount = 0; 41 step++; 42 } 43 } 44 45 return -1; 46 } 47 }