300. The longest increasing subsequence (medium)

Ideas:

The sequence representation can be discontinuous, depending on the previous solution, to use dynamic programming (dp)

 

 

Code:

class Solution {
    public int lengthOfLIS(int[] nums) {
		if(nums.length==0) return 0;
		int[] dp=new int[nums.length+1];
		//把所有dp置为1,因为就算所有都不符合,到最后一个的时候自身也符合
		Arrays.fill(dp,1);
                int res=0;

                
		for(int i=0;i<nums.length;i++){
			for(int j=0;j<i;j++){
				//此处的dp有不符合条件时"跳过"的功能
				//注意j是每次从头遍历一遍,不只是i-1
				//就算遍历到之前不符合条件的值也没事,dp就算+1,dp仍是前一个的值
                                //此处的if有跳过功能,若不满足,则dp[i]为1
				if(nums[i]>nums[j]){
					dp[i]=Math.max(dp[i],dp[j]+1);
				}
			}
                    //每次在第二重循环结束后都要比较一下
                    //因为不是dp[n-1]就是最大的,有可能dp[n-1]为1
                    res=Math.max(res,dp[i]);
		}
		    return res;
	}
}

 

break down:

1) Set up a double loop, every time i moves forward, it must be traversed once from front to back, thereby satisfying the overlap sub-problem

for(int i=0;i<n;i++){
	for(int j=0;j<i;j++)

 

2) Set the if judgment statement, there is a function to skip if the j is not satisfied

if(nums[i]>nums[j])

 

3) The following is the core code:

dp[i] has the function of caching. The current dp[i] stores the longest sequence before. If the condition of nums[i]>nums[j] is satisfied, compare dp[i] and dp[j]+1

 

Compare dp[i] and dp[j]+1:

Even if nums[i]>nums[j], if dp[j] plus the current value is still less than the longest increasing subsequence that exists before, the previous one (buffered by dp[i])

At the same time, it also satisfies the optimal sub-problem of dynamic programming

if(nums[i]>nums[j]){
    dp[i]=Math.max(dp[i],dp[j]+1);
}

 

4) Compare each time after the second recycle, because either dp[n-1] is the largest, it is possible that dp[n-1] is 1 ( the detail pit of dynamic programming )

res=Math.max(res,dp[i])

 

5) To prevent subscript overflow, when dp is declared, the length is added 1 (n+1) on the basis of n

 

6) It belongs to the second dp form: the current value depends on all the previously calculated values

Guess you like

Origin blog.csdn.net/di_ko/article/details/115228290