class Solution {
int len;
public int arrayNesting(int[] nums) {
len = nums.length;
int ans = 0;
for(int i = 0;i < len;i ++) {
if(nums[i] != len) {
ans = Math.max(ans, dfs(i, nums));
}
}
return ans;
}
int dfs(int index, int[] nums) {
int value = nums[index];
if(value == len) {
return 0;
}
nums[index] = len;
return 1 + dfs(value, nums);
}
}
变种补充:如果去掉包含0到N - 1的所有整数的条件,采用记忆化dfs
class Solution {
int[] ans;
public int arrayNesting(int[] nums) {
int len = nums.length;
ans = new int[len];
int result = 0;
for(int i = 0;i < len;i ++) {
if(ans[i] == 0) {
result = Math.max(result, dfs(i, nums));
}
}
return result;
}
int dfs(int index, int[] nums) {
int value = nums[index];
if(value == -1) {
return ans[index];
}
nums[index] = -1;
ans[index] = 1 + dfs(value, nums);
return ans[index];
}
}

这篇博客探讨了数组嵌套问题的解决方案,包括一个基础版本和一个使用记忆化搜索进行优化的版本。作者通过Java代码展示了如何在数组中寻找最深的嵌套子数组,并介绍了如何利用记忆化技术提高算法效率。
261

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



