Question:
给定一个正整数 n ,你可以做如下操作:
如果 n 是偶数,则用 n / 2替换 n 。
如果 n 是奇数,则可以用 n + 1或n - 1替换 n 。
n 变为 1 所需的最小替换次数是多少?
Resolution:
1. 记忆化map集合+深度优先搜索:
public class IntegerReplacement {
Map<Long, Integer> map = new HashMap<>();
public int IntegerReplacement(int n) {
return dfs(n * 1L);
}
int dfs(long n) {
if(n == 1) return 0;
if (map.containsKey(n)) return map.get(n);
int res = n % 2 == 0 ? dfs(n / 2) : Math.min(dfs(n + 1), dfs(n - 1));
map.put(n, ++res);
return res;
}
}

2. 记忆化map集合+广度优先搜索:
public int bfs(int n) {
if(n == 1) return 0;
Map<Long, Integer> map = new HashMa

该博客详细解析了LeetCode第397题,即如何通过贪心算法解决整数替换问题。文章探讨了两种解决方案:一是采用记忆化map集合结合深度优先搜索;二是利用记忆化策略与广度优先搜索的方法,旨在找到将正整数n转换为1所需的最小替换次数。
最低0.47元/天 解锁文章
1431

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



