LeetCode 300. Longest Increasing Subsequence -動態規劃的使用

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?

最開始的思路是貪心算法,以每個元素爲起點,終點都是尾元素,遍歷然後找出所有的上升子序列,發現這樣不行,只能過一部分數據,後來查看input數據後發現這樣的思路是不行的,因爲我的判斷條件當前元素小於下一個元素,那麼以下一個元素爲當前元素,繼續遍歷下去找大於當前元素的。這樣的貪心算法勢必會漏掉很多合適的答案。貼下錯誤代碼

class Solution {
 public static int lengthOfLIS(int[] nums) {

     if(nums.length==0)
         return 0;
    int max=-1;
    int tempMax=1;
    for(int i=0;i<nums.length;i++){
        int key=nums[i];
        for(int j=i+1;j<nums.length;j++){

            if(key<nums[j]){
                key=nums[j];
                tempMax++;
            }

        }
        if(tempMax>max)
            max=tempMax;
        tempMax=1;


    }
    return max;

    }
}

那麼貪心會漏掉,那麼肯定會想到動態規劃了,具體思路是這樣的
自底向上,從第一個元素出發,慢慢的加元素進來,看他與前面的所有子串能構成多長的子序列,都記錄下來,具體判斷方法就是加進來一個元素x,就與之前的元素y比較,如果小於之前元素,則構成上升序列,將x存儲的上升序列長度與1+y所存儲的上升子序列長度比較,誰大取誰。
這裏寫圖片描述
拿圖中元素舉例:
當只有一個元素的時候,那麼最長序列就是本身了,如元素10
繼續往下遍歷,那麼當前元素9與前一個元素10比較發現小於它,不構成上升序列,那麼此時長度還是1。
繼續往下遍歷,當元素爲2的時候發現前面兩個元素都大於它,不構成上升,所以還是1。
繼續遍歷當元素爲5的時候,發現5大於2,難麼5就可以接入2的最長上升序列後面,所以5的初始值是1加上2存儲的最長子序列值1得出2
繼續遍歷到元素爲3的時候此時比它小的只有2,加上2的值,所以此時爲2
繼續遍歷到元素爲7的時候那麼前面的元素2和元素3都小於7,此時當然取最大的相加了,因爲要最長子序列。
依次類推…

public static int max(int a,int b)
    {
        if(a>b)
            return a;
        else
            return b;
    }
    public static int lengthOfLIS(int[] nums) {
        int N=nums.length;
        if(N<=1)
            return N;
        int Max=-1;
        int keynums[]=new int[nums.length];
        for(int i=0;i<N;i++)
            keynums[i]=1;
        for(int i=1;i<N;i++)
        {
            int temmax=1;
            for(int j=i-1;j>=0;j--)
            {
                if(nums[i]>nums[j]){
                    temmax=max(temmax,keynums[j]+keynums[i]);
//                  System.out.println(temmax);
                }
            }
            keynums[i]=temmax;
            if(temmax>Max)
                Max=temmax;
        }


        return Max;
    }

這個題目做完可以做一個類似的題目Leet code 376. Wiggle Subsequence加深一下理解。

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