forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
race-car.cpp
35 lines (33 loc) · 911 Bytes
/
race-car.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Time : O(nlogn), n is the value of the target
// Space: O(n)
class Solution {
public:
int racecar(int target) {
vector<int> dp(target + 1);
for (int i = 1; i <= target; ++i) {
int k = bitLength(i);
if (i == (1 << k) - 1) {
dp[i] = k;
continue;
}
dp[i] = dp[(1 << k) - 1 - i] + k + 1;
for (int j = 0; j < k; ++j) {
dp[i] = min(dp[i], dp[i - (1 << (k - 1)) + (1 << j)] + k + j + 1);
}
}
return dp.back();
}
private:
uint32_t bitLength(uint32_t n) {
uint32_t left = 1, right = 32;
while (left <= right) {
auto mid = left + (right - left) / 2;
if ((1 << mid) > n) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
};