818. 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.
Approach #1: C++. [DFS]
class Solution {
public:
int racecar(int target) {
queue<pair<int, int>> q;
q.push({0, 1});
unordered_set<string> v;
v.insert("0_1");
v.insert("0_-1");
int steps = 0;
while (!q.empty()) {
int size = q.size();
while (size--) {
auto p = q.front(); q.pop();
int pos = p.first;
int speed = p.second;
{
int pos1 = pos + speed;
int speed1 = speed * 2;
pair<int, int> p1{pos1, speed1};
if (pos1 == target) return steps+1;
if (p1.first > 0 && p1.first < 2 * target)
q.push(p1);
}
{
int speed2 = speed > 0 ? -1 : 1;
pair<int, int> p2{pos, speed2};
string key2 = to_string(pos) + "_" + to_string(speed2);
if (!v.count(key2)) {
q.push(p2);
v.insert(key2);
}
}
}
steps++;
}
return -1;
}
};
Approach #2: Java. [DP]
class Solution {
private static int[][] m;
public int racecar(int target) {
if (m == null) {
final int kMaxT = 10000;
m = new int[kMaxT + 1][2];
for (int t = 1; t <= kMaxT; ++t) {
int n = (int)Math.ceil(Math.log(t + 1) / Math.log(2));
if (1 << n == t + 1) {
m[t][0] = n;
m[t][1] = n + 1;
continue;
}
int l = (1 << n) - 1 - t;
m[t][0] = n + 1 + Math.min(m[l][1], m[l][0] + 1);
m[t][1] = n + 1 + Math.min(m[l][0], m[l][1] + 1);
for (int i = 1; i < t; ++i) {
for (int d = 0; d <= 1; ++d) {
m[t][d] = Math.min(m[t][d], Math.min(
m[i][0] + 2 + m[t-i][d],
m[i][1] + 1 + m[t-i][d]));
}
}
}
}
return Math.min(m[target][0], m[target][1]);
}
}
Approach #3: Python. [DP]
class Solution(object):
def __init__(self): self.dp = {0: 0} def racecar(self, t):
"""
:type target: int
:rtype: int
"""
if t in self.dp: return self.dp[t]
n = t.bit_length()
if 2**n - 1 == t: self.dp[t] = n
else:
self.dp[t] = self.racecar(2**n - 1 - t) + n + 1
for m in range(n-1):
self.dp[t] = min(self.dp[t], self.racecar(t - 2**(n-1) + 2**m) + n + m + 1)
return self.dp[t]
Analysis:
http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-818-race-car/
818. Race Car的更多相关文章
- 【leetcode最短路】818. Race Car
https://leetcode.com/problems/race-car/description/ 1. BFS剪枝 0<=current position<=2*target.为什么 ...
- LeetCode 818. Race Car
原题链接在这里:https://leetcode.com/problems/race-car/ 题目: Your car starts at position 0 and speed +1 on an ...
- All LeetCode Questions List 题目汇总
All LeetCode Questions List(Part of Answers, still updating) 题目汇总及部分答案(持续更新中) Leetcode problems clas ...
- leetcode hard
# Title Solution Acceptance Difficulty Frequency 4 Median of Two Sorted Arrays 27.2% Hard ...
- Promise.race
[Promise.race] 返回最先完成的promise var p1 = new Promise(function(resolve, reject) { setTimeout(resolve, 5 ...
- golang中的race检测
golang中的race检测 由于golang中的go是非常方便的,加上函数又非常容易隐藏go. 所以很多时候,当我们写出一个程序的时候,我们并不知道这个程序在并发情况下会不会出现什么问题. 所以在本 ...
- 【BZOJ-2599】Race 点分治
2599: [IOI2011]Race Time Limit: 70 Sec Memory Limit: 128 MBSubmit: 2590 Solved: 769[Submit][Status ...
- hdu 4123 Bob’s Race 树的直径+rmq+尺取
Bob’s Race Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Probl ...
- Codeforces Round #131 (Div. 2) E. Relay Race dp
题目链接: http://codeforces.com/problemset/problem/214/E Relay Race time limit per test4 secondsmemory l ...
随机推荐
- 如果有多个集合的迭代处理情况【使用MAP】
在SQL开发过程中,动态构建In集合条件查询是比较常见的用法,在Mybatis中提供了foreach功能,该功能比较强大,它允许你指定一个集合,声明集合项和索引变量,它们可以用在元素体内.它也允许你指 ...
- 2011年浙大:Graduate Admission
题目描述: It is said that in 2011, there are about 100 graduate schools ready to proceed over 40,000 app ...
- 自然语言处理--nltk安装及wordnet使用详解
环境:python2.7.10 首先安装pip 在https://pip.pypa.io/en/stable/installing/ 下载get-pip.py 然后执行 python get-pip. ...
- bash 中的行处理命令 awk
转自:http://blog.chinaunix.net/uid-23302288-id-3785105.html
- java流类共享篇
总结: package com.aini; import java.io.*; import java.util.StringBuffere; public class tyt { public st ...
- tomcat正常启动但是访问 404
最近遇到了一些奇葩的的问题,搞了好半天才处理掉.今天就简单记录一下吧,以备不时之需. 问题描述: 在整合spring mvc项目的完成后,正常启动tomcat,发现tomcat启动成功了,但是访问本 ...
- 侯捷STL学习(六)--深入list && Iterator traits
第十三,四节 深度探索list(上,下) list Gnu2.9源代码实现 注意node代码和图示的位置 实现前闭后开,增加一个空白节点 用的分配器alloc Iterator智能指针,需要知道结点n ...
- Python数据库(一)-Mysql数据库的连接
首先需要安装pymysql模块 然后用pymysql连接mysql并执行命令来查看数据 连接mysql数据库后需要创建游标来执行SQL语句 # -*- coding:utf-8 -*- __autho ...
- create-react-app脚手架中配置sass
本文介绍如何在react中配置sass 首先将你的文件名称改成scss结尾的文件 然后安装依赖 cnpm install sass-loader node-sass --save-dev 找到node ...
- 2010.1.1 CLR 无法从 COM 上下文
今天做一个程序,sql操作,但是记录数太多,而且sql语句有复杂,就报了这样的错误: CLR 无法从 COM 上下文 0x645e18 转换为 COM 上下文 0x645f88,这种状态已持续 60 ...