【发布时间】: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