增加子序列递归 Java

Increasing Subsequence Recursive Java

我有以下问题:如果每个数字序列都单调递增(或简单递增) 序列中的数字大于或等于它前面的数字。编写一个布尔函数 increasing(int[] x, int length) 如果给定数组包含给定长度的递增子序列,则 return 为真,否则为假。准则:

我想过用一个老问题,最长递增子序列,然后比较大小,如果给定的大小比 LIS 大,则 return 错误。但是,我的 LIS 代码似乎缺少跳过数字并重复数字的情况,例如 9,7,5,4,7,1,-3,8 return false for 3 而不是 true,也适用于 3,1,1,2 return是假的。

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);
}
public static boolean increasing(int[] x, int length) {
    return increasing(x, length, x[0], 0, 0) >= length;
}

private static int increasing(int[] x, int length, int min, int i, int from) {
    if (i >= x.length)
        return 0;    

    int res = increasing(x, length, Math.max(min, x[i]), i + 1, from);

    if (x[i] >= min)
        res++;    
    if (i != from || res >= length || i + length > x.length)
        return res;
    return increasing(x, length, x[i + 1], i + 1, i + 1);
}

演示:

public static void main(String... args) {
    System.out.println(increasing(new int[] { 3, 1, 1, 2 }, 3));    // true
    System.out.println(increasing(new int[] { 9, 7, 5, 4, 7, 1, -3, 8 }, 3));   // true
}