300. Longest Increasing Subsequence 发表于 2022-01-28 DP12345678910111213141516171819202122class Solution { public int lengthOfLIS(int[] nums) { int maxLength = 1; // 定义 dp[i] 为以 nums[i] 结尾的最长严格递增子序列的长度 int[] dp = new int[nums.length]; Arrays.fill(dp, 1); for (int i = 1; i < nums.length; i++) { for (int j = 0; j < i; j++) { if (nums[j] < nums[i]) { // 可能形成更长的递增子序列 dp[i] = Math.max(dp[i], dp[j] + 1); } maxLength = Math.max(maxLength, dp[i]); } } return maxLength; }} DP + Binary Search1234567891011121314151617181920212223242526272829303132class Solution { public int lengthOfLIS(int[] nums) { // 定义 tails 数组,tails[i] 为长度为 i + 1 的严格递增子序列且 tails[i] 尽可能小 int[] tails = new int[nums.length]; int nextIndex = 0; for (int num : nums) { int insertIndex = findInsertIndex(tails, 0, nextIndex - 1, num); tails[insertIndex] = num; if (insertIndex == nextIndex) { nextIndex++; } } return nextIndex; } private int findInsertIndex(int[] tails, int left, int right, int target) { while (left <= right) { int mid = (left + right) >>> 1; if (tails[mid] < target) { left = mid + 1; } else if (tails[mid] > target) { right = mid - 1; } else { right = mid - 1; } } // now: right, left return left; }} Reference300. Longest Increasing Subsequence