您的位置:首页 > 产品设计 > UI/UE

Longest Increasing Subsequence

2016-06-16 20:57 477 查看
题目描述:

Given an unsorted array of integers, find the length of longest increasing subsequence.

For example,

Given 
[10, 9, 2, 5, 3, 7, 101, 18]
,

The longest increasing subsequence is 
[2, 3, 7, 101]
, therefore the length is 
4
.
Note that there may be more than one LIS combination, it is only necessary for you to return the length.
解题思路:
使用动态规划,dp[i]表示以第i个元素为结尾元素的最长递增序列的长度,dp[i]初始化为1。

dp[i]=max{dp[j]+1}其中j<i 且nums[i]>nums[j]

最长的递增序列的长度即为dp[i]中的最大值

AC代码如下:

class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
vector<int> dp(n, 1);
int ans = 1;
for (int i = 1; i < n; ++i){
int count = dp[i];
for (int j = 0; j < i; ++j){
if (nums[j] <= nums[i] && count < dp[j] + 1)
count = dp[j] + 1;
}
dp[i] = count;
ans = ans < dp[i] ? dp[i] : ans;
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息