[英]To find all longest increasing subsequences given an array of integers - Dynamic Programming
I'm studying dynamic programing & I came across this question in which I have to print out all the longest subsequences. 我正在研究动态编程,我遇到了这个问题,我必须打印出所有最长的子序列。 There could be more than one longest subsequence given an array.
给定一个数组可能有不止一个最长的子序列。 The program that I tried would give me only one longest subsequence but not all the longest subsequence.
我尝试的程序只给我一个最长的子序列,但不是所有最长的子序列。 How do I get all longest subsequences?
我如何得到所有最长的子序列?
//Initially I create two arrays of the length of the given input array
public static void LIS(int[] input) {
String paths[] = new String[input.length];
int[] size = new int[input.length];
for(int i=0;i<input.length; i++) {
paths[i] = input[i];
size[i] = 1;
}
for(i=1; i<input.length ; i++) {
for(j=i; j< i ; j++) {
if(input[i] > input[j] && size[i] < size[j] + 1) {
size[i] = size[j] +1;
paths[i] = paths[j] + input[i] + ""
if (maxlength < size[i]) {
maxlength = size[i];
}
}
}
}
}
My example input[] = 1,8,10,3,7,12,15 我的例子输入[] = 1,8,10,3,7,12,15
with the above algorithm I get the longest subsequence as 1,8,10,12,15 使用上述算法,我得到最长的子序列为1,8,10,12,15
I should also get 1,3,7,12,15 我也应该得到1,3,7,12,15
How can I modify the code to get this? 如何修改代码才能获得此代码?
If you want to modify this code you may store all possible predecessors for any element; 如果要修改此代码,可以存储任何元素的所有可能的前驱者; from your code:
从你的代码:
for(i=1; i<input.length ; i++) {
for(j=i; j< i ; j++) {
//if(input[i] > input[j] && size[i] < size[j] + 1) {
if(input[i] > input[j] && size[i] <= size[j] + 1) {
size[i] = size[j] +1;
//paths[i] = paths[j] + input[i] + ""
if (size[i] < size[j] + 1 )
//empty p[i]
p[i].push(j);
if (maxlength < size[i]) {
maxlength = size[i];
}
}
}
}
and then you will need to restore all possible subsequences 然后你需要恢复所有可能的子序列
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.