*[Lintcode]Longest Increasing Subsequence 最长上升子序列

来源:互联网 发布:java做贪吃蛇游戏 编辑:程序博客网 时间:2024/04/30 14:57

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 [2, 4, 5, 7], return 4

一维DP。res[i]代表最大值为nums[i]的上升子序列的长度。在i位置,每次搜索从0到i-1中,nums[j] < nums[i]的数,找到之后,代表当前i处的值可以与此前最大值为nums[j]的子序列构成上升序列。此时res[i] = res[j] + 1。反之,代表i前边的数都比其本身要大,则res[i]长度为1。

public class Solution {    /**     * @param nums: The integer array     * @return: The length of LIS (longest increasing subsequence)     */    public int longestIncreasingSubsequence(int[] nums) {        if(nums.length == 0) return 0;                int[] res = new int[nums.length];        res[0] = 1;        int max = 1;                for(int i = 1; i < nums.length; i++) {            for(int j = 0; j < i; j++) {                if(nums[i] > nums[j]) {                    res[i] = Math.max(res[i], res[j] + 1);                    max = Math.max(max, res[i]);                } else {                    res[i] = res[i] == 0 ? 1 : res[i];                }            }        }        return max;    }}


0 0
原创粉丝点击