LeetCode 300. Longest Increasing Subsequence

Posted CrazyCoder1992

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 300. Longest Increasing Subsequence相关的知识,希望对你有一定的参考价值。

Given an integer array nums, return the length of the longest strictly increasing subsequence.

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

题解:
此类型题目可以使用动态规划算法求解。
已知数组d[0…i],函数 f ( i ) f(i) f(i)代表以下标i为结尾的最长递增子序列的长度,则有: f ( 0 ) = 1 f(0) = 1 f(0)=1
将数组绘制成坐标图,x轴为数组下标,y轴为f(x),观察坐标图可知,第i个点的最长递增子序列应为其左下方区域内的最长递增子序列加上第i个点,即以下公式:
f ( i ) = m a x ( f ( 0 ) , f ( 1 ) , . . . , f ( j ) ) , 其中 j < i , d [ j ] < d [ i ] f(i) = max(f(0), f(1), ... , f(j)), 其中j < i, d[j] < d[i] f(i)=max(f(0),f(1),...,f(j)),其中j<i,d[j]<d[i]

根据递推公式实现代码:

func lengthOfLIS(input []int) int 
	maxLenArr := make([]int, len(input))
	for i := range input 
		if i == 0 
			maxLenArr[i] = 1
			continue
		
		maxLenArr[i] = 1
		for j := 0; j < i; j++ 
			if input[j] >= input[i] 
				continue
			
			if maxLenArr[j]+1 > maxLenArr[i] 
				maxLenArr[i] = maxLenArr[j] + 1
			
		
	
	maxLen := 1
	for i := range maxLenArr 
		if maxLenArr[i] > maxLen 
			maxLen = maxLenArr[i]
		
	
	return maxLen

以上是关于LeetCode 300. Longest Increasing Subsequence的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 300. Longest Increasing Subsequence

LeetCode 300. Longest Increasing Subsequence

LeetCode 300. Longest Increasing Subsequence

leetcode300.Longest Increasing Subsequence

[leetcode-300-Longest Increasing Subsequence]

LeetCode 300. Longest Increasing Subsequence