lintcode-medium-Longest Increasing Subsequence
Posted 哥布林工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Longest Increasing Subsequence相关的知识,希望对你有一定的参考价值。
Given a sequence of integers, find the longest increasing subsequence (LIS).
You code should return the length of the LIS.
What‘s the definition of longest increasing subsequence?
* The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence‘s elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.
* https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
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
动态规划:
用一个int数组表示把第i个数作为最后一个subsequence长度
所以只要后面的数比前面的数大,就更新最长子序列长度
最后遍历一边dp数组,选出最大值
public class Solution { /** * @param nums: The integer array * @return: The length of LIS (longest increasing subsequence) */ public int longestIncreasingSubsequence(int[] nums) { // write your code here if(nums == null || nums.length == 0) return 0; int[] dp = new int[nums.length]; int longest = 1; for(int i = 0; i < nums.length; i++) dp[i] = 1; for(int i = 0; i < dp.length; i++){ for(int j = i + 1; j < dp.length; j++){ if(nums[j] >= nums[i]){ dp[j] = Math.max(dp[j], dp[i] + 1); } } } for(int i = 0; i < dp.length; i++) longest = Math.max(longest, dp[i]); return longest; } }
以上是关于lintcode-medium-Longest Increasing Subsequence的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-medium-Longest Palindromic Substring