题目
- Total Accepted: 73943
- Total Submissions: 194897
- Difficulty: Medium
- Contributor: LeetCode
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.
Your algorithm should run in O(n2) complexity.
https://leetcode.com/problems/longest-increasing-subsequence/#/description思路
题目给定一个数组,希望求得其中最长的递增子序列的长度。
使用动态规划,使用a[i]保存以数组中第i个元素结尾的最长递增序列的长度,动态方程为a[i] =max{a[j] + 1|a[i] > a[j]}。
源程序
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if(nums.size() == 0)
return 0;
int a[10000],i,j;
for(i = 0;i < nums.size();i ++){
a[i] = 1;
}
for(i = 1;i < nums.size();i ++){
for(j = i - 1;j >= 0;j --)
if(nums[i] > nums[j] && (a[j] + 1) > a[i])
a[i] = a[j] + 1;
}
int max = 0;
for(i = 0;i < nums.size();i ++){
if(a[i] > max)
max = a[i];
}
return max;
}
};
本文介绍了一种使用动态规划解决最长递增子序列问题的方法,通过实例解释了算法的实现过程,并提供了一个运行在O(n^2)复杂度的C++代码示例。
232

被折叠的 条评论
为什么被折叠?



