最长上升子序列
2017-10-28 15:48
141 查看
求最长上升子序列(子序列并非必须是连续的)的内容,典型的dp问题
解法如下
假定f(i)表示为前i个数字中以第i个数字结尾的
LIS 长度则
f(j)=max(f(i)+1) i<j && l[j]>l[i]
=1 others
解法如下
假定f(i)表示为前i个数字中以第i个数字结尾的
LIS 长度则
f(j)=max(f(i)+1) i<j && l[j]>l[i]
=1 others
#include<iostream> #include<vector> #include<algorithm> using namespace std; int longestIncreasingSubsequence(const vector<int>&v){ if(v.empty())return 0; vector<int>ret(v.size(),1); for(int i=1;i!=ret.size();++i){ for(int j=0;j!=i;++j){ if(ret[i]<ret[j]+1 && v[i]>v[j])ret[i]=ret[j]+1; } } return *max_element(ret.begin(),ret.end()); } vector<int>LIS(const vector<int>&v){ if(v.empty())return vector<int>{}; vector<int>ret(v.size(),1); for(int i=1;i!=ret.size();++i){ for(int j=0;j!=i;++j){ if(ret[i]<ret[j]+1 && v[i]>v[j])ret[i]=ret[j]+1; } } auto end=max_element(ret.begin(),ret.end()); auto num=*end; vector<int>res(num); auto j=end-ret.begin(); for(;j>=0;--j){ if(ret[j]==num){ --num; res[num]=v[j]; } } return res; } int main(){ vector<int>v{4,2,4,5,3,7}; cout<<longestIncreasingSubsequence(v)<<endl; auto r=LIS(v); for(auto i:r) cout<<i<<","; cout<<endl; }
相关文章推荐
- sdutacm-最长上升子序列
- 最长上升子序列LIS(Longest Increasing Subsequence)
- 最长上升子序列nlogn算法
- POJ 1631 Bridging signals 最长上升子序列
- 最长上升子序列
- 最长上升子序列LIS算法实现
- 最长上升子序列
- POJ 2533 Longest Ordered Subsequence(DP 最长上升子序列)
- HDU 1069 Monkey and Banana(LIS最长上升子序列)
- HDU-1159 Common Subsequence 最长上升子序列
- HDU - 1025 Constructing Roads In JGShining's Kingdom (nlogn 最长上升子序列)
- HDU 1950 最长上升子序列
- HDU1087最长上升子序列
- POJ 1836 Alignment(DP最长上升子序列)
- hdu 4512 吉哥系列故事——完美队形I(最长公共上升子序列)
- poj 2533 Longest Ordered Subsequence(LIS(最长上升子序列))
- hdu 5489(最长上升子序列)
- 独立集-最长上升子序列的延伸
- UESTC-1006 最长上升子序列(最长递减子序列做法+贪心策略)
- hdu 1025 Constructing Roads In JGShining's Kingdom 最长上升子序列