题目:
求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}
思路:和最长上升子序列一样,用动态规划解决
据说可以做到O(nlogn)但是挺麻烦的,还是习惯用O(n*n)
void Print(vector<int> &data,vector<int> &dp,int k)
{
for (int i = k-1;i>=0;i--)
{
if(dp[i]+1==dp[k] && data[i]>data[k])
{
Print(data,dp,i);
break;
}
}
cout<<data[k]<<" ";
}
void lms(vector<int> &data)
{
int n = data.size();
vector<int> dp(n,0);
int max = 0;
int maxindex = 0;
for (int i=0; i<n;++i)
{
dp[i] = 1;
for (int j =0;j<i;j++)
{
if(data[j]>data[i] && dp[j]+1 > dp[i])
dp[i] = dp[j] + 1;
}
if(dp[i]>max)
{
max = dp[i];
maxindex = i;
}
}
Print(data,dp,maxindex);
cout<<endl<<"最长递减子序列长度:"<<max;
}
int main(void)
{
int a[]={9,4,3,2,5,4,3,2};
vector<int> vec(a,a+8);
lms(vec);
return 0;
}