300. Longest Increasing Subsequence
題目描述:Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given[10, 9, 2, 5, 3, 7, 101, 18]
,
The longest increasing subsequence is[2, 3, 7, 101]
, therefore the length is4
. Note that there may be more than one LIS combination, it is only necessary for you to return the length.Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
題目大意:給定一個數組,找出數組中的最長上升子序列
思路:DP,dp[i]表示以第i個位置爲結尾處的最長子序列
代碼
package DP; import java.util.Arrays; /** * @Author OovEver * @Date 2017/12/17 17:13 */ public class LeetCode300 { public static int lengthOfLIS(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int[] dp = new int[nums.length]; int max = 1; Arrays.fill(dp, 1); for(int i=0;i<nums.length;i++) { for(int j=0;j<i;j++) { if (nums[i] > nums[j] && dp[j]+1>dp[i]) { dp[i] = dp[j] + 1; } } max = Math.max(max, dp[i]); } return max; } }