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.
解题思路 —— 动态规划
- 记
dp[i+1]
: 以 nums[i]
结尾的最长上升子序列 - 则
dp[i+1] = max(dp[j]...) + 1
其中 j
是 0
到 i
中使得 nums[j] < nums[i]
的数字 - 最长上升子序列是
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
}