Leetcode - Longest Increasing Subsequence

Question

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 is 4. 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?


Java Code

/**
 * 動態規劃問題:
 *      求數組的最長增量子序列(LIS)的長度
 * 解題思路:
 *      尋找狀態轉移關係,發現數組nums在位置i處的LIS依賴於之前每個位置j處的LIS,
 *      當nums[i]的值大於nums[j]時,j處的LIS可以繼續增長,
 *      再比較每一個j處LIS增長之後的長度,取最大長度作爲當前位置i處的LIS
 * 
 * @author 漫遊者
 */
public int lengthOfLIS(int[] nums) {
    //用於儲存nums數組中每個元素處的LIS長度
    int[] lis = new int[nums.length];
    int maxLength = 0;
    for(int i = 0; i < nums.length; ++i) {
        //當前元素處的LIS長度至少爲1
        lis[i] = 1;
        for(int j = 0; j<i; ++j) {
            //如果在當前位置i之前有更小的元素,且其LIS長度不小於當前的LIS長度,則更新
            if(nums[j] < nums[i] && lis[j] >= lis[i])
                lis[i] = lis[j] + 1;
        }

        //每次更新maxLength
        if(lis[i] > maxLength)
            maxLength = lis[i];
    }
    return maxLength;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章