题目大意:
给定一个正整数 n ,你可以做如下操作:
如果 n 是偶数,则用 n / 2替换 n 。
 如果 n 是奇数,则可以用 n + 1或n - 1替换 n 。
 n 变为 1 所需的最小替换次数是多少?
链接:https://leetcode-cn.com/problems/integer-replacement
示例 1:
输入:n = 8
 输出:3
 解释:8 -> 4 -> 2 -> 1
 示例 2:
输入:n = 7
 输出:4
 解释:7 -> 8 -> 4 -> 2 -> 1
 或 7 -> 6 -> 3 -> 2 -> 1
 示例 3:
输入:n = 4
 输出:2
  
提示:
1 <= n <= 2^31 - 1
解题报告:
可以用记忆化bfs去解这道题。
贪心的思路如下:

AC代码1:(记忆化bfs)
class Solution {
public:int integerReplacement(int n) {map<long long, int> mp;mp[n] = 0;queue<long long> q;q.push(n);while(q.size()) {long long cur = q.front();q.pop();if(cur == 1) return mp[1];if(cur%2 == 0 && cur != 0) {if(mp.count(cur/2) == 0) {q.push(cur/2);mp[cur/2] = mp[cur]+1;}}else {if (cur > 0){if(mp.count(cur-1) == 0) {q.push(cur-1);mp[cur-1] = mp[cur]+1;}}  if(mp.count(cur+1) == 0) {mp[cur+1] = mp[cur]+1;q.push(cur+1);}} }return mp[1];}
};AC代码2:(贪心)
class Solution {
public:int integerReplacement(long long n) {int ans = 0;while (n != 1) {if (n % 2 == 0) {n >>= 1;} else {if (n != 3 && (n%4) == 3) n++;else n--;}ans++;}return ans;}
};