我有以下问题:如果每个数字序列被称为单调递增(或简单递增)
序列中的数字大于或等于其前面的数字。编写一个 boolean 函数 increasing(int[] x, int length)
,如果给定数组包含给定长度的递增子序列,则返回 true,否则返回 false。指南:
- 根本没有循环,只有递归
- 没有列表和导入(因此没有 map 等)和
?
- 不更改函数的签名
increasing(int[] x, int length)
- 您可以添加私有(private)函数,但不能添加整数/boolean 值等。
我想到用一个老问题,最长递增子序列,然后比较大小,如果给定的大小比LIS大,就会返回false。然而,我的 LIS 代码似乎缺少跳过数字并重复数字的情况,例如 9,7,5,4,7,1,-3,8
返回 false 为 3 而不是true,对于 3,1,1,2
也返回 false。
public static boolean increasing(int[] x, int length) {
int i = 0;
int ans = longestIncreasing(x, length, i);
return (ans >= length);
}
private static int longestIncreasing(int[] arr, int n, int i) {
if (n == 0) {
return 1;
}
int m = 1, temp;
if (arr[i++] < arr[n--]) {
temp = 1 + longestIncreasing(arr, n, i);
if (temp > m) {
m = temp; // m = max(m, 1 + _lis(arr, i));
}
}
else {
longestIncreasing(arr, n--, i++);
}
return m;
}
最佳答案
在这种情况下,找到最长的递增序列似乎是更难解决的问题。查找特定长度的连续序列的问题只需要在递归调用堆栈的每一层的索引变量中添加一个,并与目标长度进行比较。因此,在简单的情况下,您的问题可以这样解决:
public static boolean increasing(int[] x, int length) {
return increasing(x, length, 0);
}
private static boolean increasing(int[] x, int length, int depth) {
if (x.length < length) return false;
if (depth >= length) return true;
if (depth > 0 && x[depth - 1] > x[depth]) return false;
return increasing(x, length, depth + 1);
}
当您必须考虑非连续项目的序列时,事情会变得更加复杂。在这种情况下,当您遇到小于其前一个元素的元素时,您不必立即返回 false,而是只需在不增加深度的情况下向下移动调用堆栈,并跟踪比较时要跳过的元素数量序列的最后两项。 (注意,这需要额外的检查以防止递归超出数组大小):
public static boolean increasing(int[] x, int length) {
return increasing(x, length, 0, 0);
}
private static boolean increasing(int[] x, int length, int depth, int skip) {
if (x.length < length) return false;
if (depth >= length) return true;
if (depth + skip >= x.length) return false;
if (depth > 0 && x[depth - 1] > x[depth + skip]) {
return increasing(x, length, depth, skip + 1);
}
return increasing(x, length, depth + 1, 0);
}
关于java - Java 增加子序列递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53737492/