[Likou] 300. Longest increasing subsequence
Given an array of integers nums, find the length of the longest strictly increasing subsequence in it.
A subsequence is a sequence derived from an array by removing (or not removing) elements from the array 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].
Example 1:
Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], so the length is 4.
Example 2:
Input: nums = [0,1,0,3,2,3]
Output: 4
Example 3:
Input: nums = [7,7,7,7,7,7,7]
Output: 1
提示:
1 <= nums.length <= 2500
- 1 0 4 10^4 104 <= nums[i] <= 1 0 4 10^4 104
answer
Retrace five steps:
-
Determine the meaning of the dp array and the subscript, which
dp[j]
means:i
The length of the longest ascending subsequence ending with the th number. Notenums[i]
that must be selected . -
Determine the recurrence formula
-
How to initialize dp array
dp[0]=1 -
Determine the order of traversal.
Normal traversal is from left to right. -
Take an example to deduce the dp array.
The input is:10 9 2 5 3 7 101
, and the output is:1 1 1 2 2 3 4
The input is:5 7 1 9 4 6 2 8 3
, and the output is:1 2 1 3 2 3 2 4 3
class Solution {
public int lengthOfLIS(int[] nums) {
if (nums.length == 0) {
return 0;
}
int[] dp = new int[nums.length];
dp[0] = 1;
int maxans = 1;
for (int i = 1; i < nums.length; i++) {
// 默认以i为结尾的最长串是1,只有它本身
dp[i] = 1;
// 从0 判断到 i
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
// 取dp数组中的最大值
maxans = Math.max(maxans, dp[i]);
}
return maxans;
}
}
When calculating state dp[i], it takes O(n) time to traverse all states of dp[0…i−1], so the total time complexity is O( n 2 n^2n2)