397. 整数替换
思路:爆搜
直接模拟,搜索过程中记录已经搜索过的值,保证时间复杂度为O(log(n))O(log(n))O(log(n))级别,还需要O(log(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;
}
};
本文介绍了一种通过递归搜索实现的整数替换算法。该算法利用哈希表记录已解决子问题的答案来减少重复计算,确保了算法的时间复杂度为O(log(n))级别。文章详细解释了算法的具体实现过程及其优化策略。

被折叠的 条评论
为什么被折叠?



