首页 > 其他分享 >LeetCode: 300. Longest Increasing Subsequence

LeetCode: 300. Longest Increasing Subsequence

时间:2022-12-05 18:01:10浏览次数:39  
标签:val nums 300 length int Subsequence ans Increasing dp


LeetCode: 300. Longest Increasing Subsequence

题目描述

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

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

Note:

  • There may be more than one LIS combination, it is only necessary for you to return the length.
  • Your algorithm should run in ​​O(n^2)​​ complexity.

解题思路 —— 动态规划

  1. 记 ​​dp[i+1]​​​: 以 ​​nums[i]​​ 结尾的最长上升子序列
  2. 则 ​​dp[i+1] = max(dp[j]...) + 1​​​ 其中 ​​j​​​是 ​​0​​​ 到 ​​i​​​ 中使得 ​​nums[j] < nums[i]​​ 的数字
  3. 最长上升子序列是 ​​dp​​ 数组中的最大值

AC 代码

func lengthOfLIS(nums []int) int {
// dp[i]: 以 nums[i] 结尾的最长上升子序列
dp := []int{0}

for i := 1; i <= len(nums); i++{
dp = append(dp, 1)
for j := 0; j < i; j++ {
if (j == 0 || nums[j-1] < nums[i-1]) && dp[j] + 1 > dp[i]{
dp[i] = dp[j] + 1
}
}
}

ans := 0
for _, val := range dp {
if val > ans {
ans = val
}
}

return ans
}


标签:val,nums,300,length,int,Subsequence,ans,Increasing,dp
From: https://blog.51cto.com/u_15903085/5913220

相关文章