【问题标题】:Complexity of recursion in nested loops in Dynamic and Non-dynamic programming动态和非动态编程中嵌套循环中递归的复杂性
【发布时间】:2020-06-14 01:40:32
【问题描述】:

我用 Java 编写了一个基本的动态编程示例(如下所示),它解决了最长递增子序列问题 (https://en.wikipedia.org/wiki/Longest_increasing_subsequence)。

该函数有效,但对于家庭作业,我试图找出该算法与其非动态等效算法的时间复杂度。

我相信动态版本是 O(n^2) 但对于非动态等价物我很困惑。我尝试过编写非动态版本但失败了,但我认为它将由嵌套 (2) for 循环中的递归调用组成。这是否意味着指数时间复杂度?甚至是阶乘时间复杂度?

如果能帮助我破解这个复杂性难题,甚至生成我在下面编写的函数的非动态、递归等价物,我将不胜感激。

提前致谢!


   public static int longest(int[] array) {

        int n = array.length;

        int[] results = new int[n];

        for(int i = 0; i < n; i++) {
            results[i] = -1;
        }

        int max = 1;
        for(int j = 1; j <= n; j++) {
            int current = memoized_longest(array, j, results);
            if(current > max) {
                max = current;
            }
        }

        return max;
    }


    public static int memoized_longest(int[] array, int n, int[] results) {

        if(results[n-1] >= 0) {
            return results[n-1];
        }

        if(n == 1) {
            results[n-1] = 1;
            return results[n-1];
        }

        int q = 1;

        for(int i = n - 1; i >= 0; i--) {
            if(array[i] < array[n - 1]) {
                 q = Math.max(q, 1 + memoized_longest(array, i+1, results));
            }
        }

        results[n-1] = q;
        return q;
    }

【问题讨论】:

    标签: algorithm recursion time-complexity dynamic-programming


    【解决方案1】:

    你差点就吃完了:

    public static int longest(int[] array) {
      int q = 0;
      for (int i = 0; i < array.length; i++) {
        q = Math.max(q, longest_at(array, i));
      }
      return q;
    }
    
    public static int longest_at(int[] array, int i) {
      int q = 1;
      for (int j = 0; j < i; j++) {
        if (array[j] < array[i]) {
          q = Math.max(q, 1 + longest_at(array, j));
        }
      }
      return q;
    }
    

    longest_at 返回在位置i 结束的最长递增子序列的长度。将递归 DP 算法转换为普通递归算法,只需放弃记忆即可。

    对于运行时,我们有如下递归关系:

    T(n)

    T(n) 是longest_at(n) 的运行时间。为了计算longest_at(n),我们必须(可能,如果位置n之前的所有元素都小于array[n])计算longest_at(1)longest_at(2),直到longest_at(n-1)。这反映在递归关系中。

    如果 T(1) = 1,则 T(n) = 2^n - 1 是一个解。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多