Longest Increasing Subsequence - Solution 2

Question

from lintcode

Given a sequence of integers, find the longest increasing subsequence (LIS).

You code should return the length of the LIS.

Clarification

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_increasing_subsequence

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

Idea

NOTE: this solution does not reach a good time complexity. But it's a good practice for recursion exercise.
Start from each element, and try to reach the end of the array to count the maximum increasing sequence length.
My previous solution has better performance, which starts from 0 and tries to reach each element to count the maximum increasing sequence length.
I will provide an analysis regarding the two methods later.

import java.util.Arrays;

public class Solution {
    /**
     * @param nums: An integer array
     * @return: The length of LIS (longest increasing subsequence)
     */
    public int longestIncreasingSubsequence(int[] nums) {
        /**
         *  f(i) means the length of LIS that contains nums[i]
         */
        if (nums.length == 0) return 0;
        int[] f = new int[nums.length];

        for (int i = 0; i < f.length; i++)
            f[i] = Integer.MIN_VALUE;

        for (int i = 0; i < f.length; i++) {
            if (f[i] < (nums.length - (i+1))) {
                f[i] = compute(f, nums, i, 1, i);
            }            
        }


        return Arrays.stream(f).max().getAsInt();
    }

    /**
     * @param f f(i) means the length of the LIS that contains nums[i]
     * @param nums numbers array
     * @param i current element position
     * @param length the accumulated increasing sequence length
     * @param pathEndIndex the last element of the sequence
     * @return the length of the LIS that contains nums[i]
     */
    private int compute(int[] f, int[] nums, int i, int length, int pathEndIndex) {
        if (i == nums.length)
            return length;
        int pathLen = 0;
          
        if (nums[i] > nums[pathEndIndex]) {
            int newPathEnd = i;
            pathLen = compute(f, nums, i + 1, length + 1, newPathEnd);
        }
        pathLen = Math.max(pathLen, compute(f, nums, i + 1, length, pathEndIndex));
        f[i] = Math.max(pathLen, f[i]);
        return f[i];
    }
}

你可能感兴趣的:(Longest Increasing Subsequence - Solution 2)