动态规划:最长上升子序列

输入n个数,求出这个序列中最长的上升子序列的长度。

如:4 2 3 1 5;(2 3 5是最长上升子序列,长度为3)

#include <iostream>
#include <algorithm>
using namespace std;

int n;
const int maxn = 1000 + 20;
int a[maxn];
int dp[maxn];

/*
5
4 2 3 1 5
*/

void solve()
{
    int res = 0;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    for (int i = 0; i < n; i++)
    {
        dp[i] = 1;
        for (int j = 0; j < i; j++)
        {
            if (a[j] < a[i]) 
            {
                dp[i] = max(dp[i], dp[j] + 1);
            }
        }
        res = max(res, dp[i]);
    }
    printf("%d\n", res);
}

int main()
{
    solve();
    return 0;
}

 

posted @ 2018-03-07 19:30  douzujun  阅读(239)  评论(0编辑  收藏  举报