题目链接:397. 整数替换 - 力扣(LeetCode) (leetcode-cn.com)
难度:Medium
BFS 最短路,注意可能会爆 。
struct node{
int step;
long long v;
};
class Solution {
public:
int integerReplacement(int n) {
queue<node>q;
node t = {0,(long long)n};
q.push(t);
while(!q.empty()){
t = q.front();
q.pop();
if(t.v == 1){
return t.step;
}
if(t.v & 1){
q.push({t.step+1, t.v+1});
q.push({t.step+1, t.v-1});
} else {
q.push({t.step+1, t.v/2});
}
}
int ans = 0;
return ans;
}
};