示例解法
这道题目的dp要仔细分析。分析过程写在了注释中(个人习惯…)。
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
|
class Solution: def racecar(self, target: int) -> int: dp = [0] + [float('inf')] * target for i in range(1, target + 1): n = i.bit_length() if i == (1 << n) - 1: dp[i] = n else: dp[i] = dp[(1 << n) - 1 - i] + n + 1 for k in range(n - 1): dp[i] = min(dp[i], dp[i - (1 << (n - 1)) + (1 << k)] + n + k + 1) return dp[target]
|