LeetCode Longest Increasing Subsequence

原创 2015年11月17日 21:17:33

题目:

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;
	}
}



版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

Longest Increasing Subsequence -- Leetcode

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

【Leetcode】Longest Increasing Subsequence

Longest Increasing SubsequenceGiven an unsorted array of integers, find the length of longest increa...

精选:深入理解 Docker 内部原理及网络配置

网络绝对是任何系统的核心,对于容器而言也是如此。Docker 作为目前最火的轻量级容器技术,有很多令人称道的功能,如 Docker 的镜像管理。然而,Docker的网络一直以来都比较薄弱,所以我们有必要深入了解Docker的网络知识,以满足更高的网络需求。

Leetcode - Longest Increasing Subsequence

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

Leetcode Longest Increasing Subsequence

Leetcode Longest Increasing Subsequence,本算法主要集中了动态归划和二分搜索,算法复杂度为o(n logn),相关代码如下:#include #include/*...

[LeetCode]Longest Increasing Subsequence

这是一道典型的动态规划问题,通常有两种解法,一种自然的思想时间复杂度为O(n^2),而另一种巧妙地思路可以利用二分查找把时间复杂度降低到O(nlogn)。下面分别介绍这两种做法。

LeetCode Longest Increasing Subsequence

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

leetcode 300. Longest Increasing Subsequence

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

Leetcode 300. Longest Increasing Subsequence

-题目- Given an unsorted array of integers, find the length of longest increasing subsequence. For ...

leetcode-300-Longest Increasing Subsequence

题目:Longest Increasing Subsequence 最长升序子序列 Given an unsorted array of integers, find the length of l...

leetcode 300. Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence. For examp...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)