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

LeetCode Longest Increasing Subsequence

2015-11-17 21:17 435 查看
题目:

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.

给定一个数组,然后计算数组中的最长递增子序列的长度,要求在O(n^2)的时间复杂度内完成。首先一开始这题我不是很理解,以为是这个最长递增子序列,是要求每一段中都是连续递增的,其实它是可以断断续续的,也就是说其实它是可以中间断的,不一定要连续,那么考虑采用动态规划来做,其实这也是一道非常典型的动态规划的题目,考虑当前的状态和状态转移方程。首先我们看到当循环到当前这个数组下标的值时,考虑与之前的每一个数组下标中的元素的值的大小比较情况,其实也就是d(i)
= max{1,d(j) + 1},其中j < i,A[j] <= A[i],就是在内层循环中得每一个都得和当前的比,如果是比当前的那个值大的,那么当前位置对应的那个d(j)值就加1,然后赋给d(i),每次在内层循环完之后,就判断和最大的那个比较,如果比最大的那个还大,那么就赋值,否则就不用赋值。

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