397. 整数替换
思路:爆搜
直接模拟,搜索过程中记录已经搜索过的值,保证时间复杂度为 O ( l o g ( n ) ) O(log(n)) O(log(n))级别,还需要 O ( l o g ( n ) ) O(log(n)) O(log(n))的栈空间
typedef long long LL;
class Solution {
public:
unordered_map<LL, int> dp;
int integerReplacement(int n) {
return f(n);
}
LL f(LL n) {
if (dp.count(n)) return dp[n];
if (n == 1) return 0;
else if (n & 1) return dp[n] = min(f(n + 1), f(n - 1)) + 1;
else return dp[n] = f(n / 2) + 1;
}
};