Given a sequence of integers, find the longest increasing subsequence (LIS).
You code should return the length of the LIS.
Example
For [5, 4, 1, 2, 3], the LIS is [1, 2, 3], return 3
For [4, 2, 4, 5, 3, 7], the LIS is [4, 4, 5, 7], return 4
state: dp[i]表示前i个数中以第i个为结尾的LIS长度
function: dp[i] = max{dp[j] + 1}--> if (A[j] <= A[i])
initial: dp[0] = 1; dp[i] = 1;//如果不初始化dp[i] 例如数组【5,1】dp[1]就为0了
return max{dp[i]}
public class Solution { /** * @param nums: The integer array * @return: The length of LIS (longest increasing subsequence) */ public int longestIncreasingSubsequence(int[] nums) { int n = nums.length; if (nums == null || n == 0) { return 0; } int[] dp = new int[n]; int max = 0; dp[0] = 1; for (int i = 1; i < n; i++) { dp[i] = 1; for (int j = 0; j < i; j++) { if (nums[i] >= nums[j]) { dp[i] = Math.max(dp[i], dp[j] + 1); } } max = Math.max(dp[i], max); } return max; } }
没有评论:
发表评论