打印所有可能的最长减少的子序列
我有一个整数数组A [1 ... N]。现在我想打印所有最长的减少子数。我经历了大部分的教程,但所有的教程只打印一个LDS。假设LDS的长度是5,那么大多数教程只打印一个长度为5的LDS。 但我想打印所有可能的LDS。如何这样做吗?可以在O(nlongn)时间内完成。伪代码会更有帮助。打印所有可能的最长减少的子序列
这是比较容易理解的想法,如果你未优化从教程的算法,并使用更简单的N^2
算法,它可以线性回溯而不是在地图上查找。然后修改打印序列的代码以向后搜索先前的元素,而不是将其存储在vector<int> pre
中。然后你可以用简单的递归回溯器打印所有序列:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print_all(
const vector<int> seq
, const vector<int>& len
, int max, int pos
, vector<int>& sofar) {
if (max == 0) {
for (int i = sofar.size()-1 ; i >= 0 ; i--)
cout << sofar[i] << " ";
cout << endl;
return;
}
int val = pos < seq.size() ? seq[pos] : -1;
for (int i = pos-1 ; i >= 0 ; i--) {
if (len[i] == max && seq[i] > val) {
sofar.push_back(seq[i]);
print_all(seq, len, max-1, i, sofar);
sofar.erase(sofar.end()-1);
}
}
}
int main() {
int data[] = {5, 30, 2, 17, 92, 11, 7, 10, 2, 1};
vector<int> seq(data, data+10);
vector<int> len(seq.size());
for (int i = 0 ; i < seq.size() ; i++) {
len[i] = 1;
for (int j = i-1 ; j >= 0 ; j--)
if (seq[j] > seq[i] && len[j]+1 > len[i])
len[i] = len[j]+1;
}
int max = *max_element(len.begin(), len.end());
cerr << max << endl;
vector<int> sofar;
print_all(seq, len, max, seq.size(), sofar);
}
dasblinkenlight ::程序给出的病例数据不正确的输出[] = {5,23,100,10,4,90,65,11,18,10},其给出的LDS长度= 4,并且LDS是 {90 65 18 10}, {90 65 11 10} 如何正确的答案是LDS长度= 5,并且LDS是 {100 90 65 18 10}, {100 90 65 11 10} – 2012-04-15 13:21:42
dasblinkenlight ::程序给出不正确的输出数据[] = {5, 23,100,10,4,90,65,1 1,18,10},其LDS长度= 4,LDS是{90 65 18 10},{90 65 11 10}正确的答案是LDS长度= 5,LDS是{100 90 65 18 10} ,{100 90 65 11 10} – 2012-04-15 13:35:35
dasblinkenlight ::你可以在这里查看:: http://ideone.com/SP4wc – 2012-04-15 13:44:56
您可以跟踪你所有的时间最长(迄今为止)的子序列,你走:
// If you have only one element, that is the longest descending subsequence
// Otherwise store first element as previous
if: current element is less than (or equal to) previous
// decreasing
increase current subsequence length
add element to current subsequence
else:
// increasing
set current subsequence length to 0
empty current subsequence
if: current subsequence is longer than current maximum
invalidate all current max subsequences
set current maximum subsequence length to current subsequence length
add current subsequence to set of longest subsequences
else if: current subsequence is same size as current maximum
add current subsequence to set of longest subsequences
什么教程?你到目前为止有什么?任何你有特定问题的代码? – Femaref 2012-04-15 11:50:34
尝试使用精美的数据结构,发布一些示例代码,展示您尝试过的东西等。基本上_TRIE_ – Baz1nga 2012-04-15 11:55:14
@Femaref:https://comeoncodeon.wordpress.com/2009/08/12/longest-increasing-subsequence-lis /这是我所指的。这是虽然LIS,但它不会成熟很多。它只打印LAST LDS,如果倍数退出。我想要打印所有的LDS – 2012-04-15 11:55:57