Skip to content

Latest commit

 

History

History

818

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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:
    <ul>
    	<li><code>position += speed</code></li>
    	<li><code>speed *= 2</code></li>
    </ul>
    </li>
    <li>When you get an instruction <code>'R'</code>, your car does the following:
    <ul>
    	<li>If your speed is positive then <code>speed = -1</code></li>
    	<li>otherwise <code>speed = 1</code></li>
    </ul>
    Your position stays the same.</li>
    

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.

 

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 <= 104

Companies:
Google

Related Topics:
Dynamic Programming

Solution 1. BFS

// OJ: https://leetcode.com/problems/race-car/
// Author: github.com/lzl124631x
// Time: O(?)
// Space: O(?)
// Ref: https://leetcode.com/problems/race-car/discuss/124312/Javascript-Python3-C%2B%2B-.-BFS-solutions
class Solution {
public:
    int racecar(int target) {
        queue<array<int, 2>> q;
        q.push({0, 1});
        unordered_map<int, unordered_set<int>> seen;
        seen[0].insert(1);
        int step = 0;
        while (true) {
            int cnt = q.size();
            while (cnt--) {
                auto [pos, speed] = q.front();
                q.pop();
                if (pos == target) return step;
                vector<array<int, 2>> cand;
                if (abs(target - (pos + speed)) < target) cand.push_back({ pos + speed, 2 * speed }); // Only continue moving in the current direction if doing so reduces the distance.
                cand.push_back({ pos, speed < 0 ? 1 : - 1 }); // reverse direction
                for (auto &[pos, speed] : cand) {
                    if (seen[pos].count(speed)) continue;
                    seen[pos].insert(speed);
                    q.push({pos, speed});
                }
            }
            ++step;
        }
        return -1;
    }
};