最長遞增子序列和ta的衍生題
阿新 • • 發佈:2020-12-22
最長遞增子序列
這是一切開始的地方
class Solution { public int lengthOfLIS(int[] nums) { if (nums.length == 0) return 0; int res = 1; int[] dp = new int[nums.length]; Arrays.fill(dp, 1); for (int i = 1; i < nums.length; i++) { for (intj = 0; j < i; j++) { if (nums[i] > nums[j]) { dp[i] = Math.max(dp[i], dp[j] + 1); } } res = Math.max(res, dp[i]); } return res; } }
無重疊區間
根據第二個元素先排序,至於原由你細品。最長上升子序的個數就是無重疊區間的個數。(貪心是最優解,這樣只是提供了另一個思路)
class Solution { public int eraseOverlapIntervals(int[][] intervals) { if (intervals.length == 0) return 0; Arrays.sort(intervals, (o1, o2) -> o1[1] - o2[1]); int[] dp = new int[intervals.length]; Arrays.fill(dp, 1); int res = 1; for (int i = 1; i < intervals.length; i++) {for (int j = 0; j < intervals.length; j++) { if (intervals[i][0] >= intervals[j][1]) { dp[i] = Math.max(dp[j] + 1, dp[i]); } } res = Math.max(dp[i], res); } return intervals.length - res; } }
用最少數量的箭引爆氣球
和上面的思路一樣,有多少不重疊的區間就射多少箭。你這樣想,不重疊的區間就是至少射的箭的數量,只要射得是重疊區間的交集就可以順帶把重疊區間射掉。(同樣貪心跟簡單,這只是另一種思路)
class Solution { public int findMinArrowShots(int[][] points) { if (points.length == 0) return 0; Arrays.sort(points, (o1, o2) -> (o1[1] < o2[1] ? -1 : 1)); int res = 1; int[] dp = new int[points.length]; Arrays.fill(dp, 1); for (int i = 0; i < points.length; i++) { for (int j = 0; j < i; j++) { if (points[i][0] > points[j][1]) { dp[i] = Math.max(dp[j] + 1, dp[i]); } } res = Math.max(res, dp[i]); } return res; } }