标签:end min closed i++ etc http lap targe ++
https://leetcode.com/problems/race-car/description/
1. BFS剪枝 0<=current position<=2*target。为什么2*target有点不太明白
1 class Solution { 2 public: 3 int dp[10002]; 4 struct Node{ 5 int pos; 6 int speed; 7 int step; 8 Node(int p,int s,int ss){ 9 pos=p; 10 speed=s; 11 step=ss; 12 } 13 }; 14 int racecar(int target) { 15 queue<Node> Q; 16 set<pair<int,int> > vis; 17 Q.push(Node(0,1,0)); 18 vis.insert({0,1}); 19 while(!Q.empty()){ 20 Node q=Q.front(); 21 Q.pop(); 22 if(q.pos==target) return q.step; 23 if(vis.find({q.pos+q.speed,q.speed*2})==vis.end()&&q.pos+q.speed>=0&&q.pos+q.speed<=2*target){ 24 vis.insert({q.pos+q.speed,q.speed*2}); 25 Q.push(Node(q.pos+q.speed,q.speed*2,q.step+1)); 26 } 27 if(vis.find({q.pos,q.speed>0?-1:1})==vis.end()){ 28 vis.insert({q.pos,q.speed>0?-1:1}); 29 Q.push(Node(q.pos,q.speed>0?-1:1,q.step+1)); 30 } 31 } 32 return -1; 33 } 34 };
2. Dijkstra,官方题解,没太看懂
3. DP
1 class Solution { 2 public: 3 int dp[10002]; 4 int racecar(int target) { 5 if(dp[target]!=0) return dp[target]; 6 int bound; 7 for(int i=0;i<32;i++){ 8 if((1<<i)-1==target) return dp[target]=i; 9 if((1<<i)-1>target){ 10 bound=i; 11 break; 12 } 13 } 14 dp[target]=bound+1+racecar((1<<bound)-1-target); 15 for(int i=0;i<bound-1;i++){ 16 dp[target]=min(dp[target],bound-1+1+i+1+racecar(target-(((1<<(bound-1))-1)-((1<<i)-1)))); 17 } 18 return dp[target]; 19 } 20 };
标签:end min closed i++ etc http lap targe ++
原文地址:https://www.cnblogs.com/itcsl/p/9061542.html