Java implementation - the longest sequence rise

This problem is a dynamic programming problem, if violence to solve it, every number has selected or not selected the two states, and then determine whether the increase in sequence, and if so, updates the length of the longest, until you enumerate all cases. However, when there are n elements, which will reach the complexity O (2 ^ n), which is obviously unbearable.

Therefore, the use of dynamic programming can significantly reduce complexity.

Order dp [i] expressed in a [i] at the end of the longest length of the rising sequence, there are two possibilities for a [i] is:

1) If there is more than a [i] small numbers a [j] (J before i <i), and dp [j] + 1> dp [i] ( i.e., the a [i] to put a [j ] after the end of the sequence to which the current is greater than the length a [i] in the length of the end of the sequence), then put a [i] after before put to a [j] end of the sequence, and make the length + ( i.e. DP [I] DP = [J] + 1);
2) if all of a [i] before it than large, then only a [i] as a sub-sequence itself, its length is 1.

public class Solution {
    /**
     * @param nums: The integer array
     * @return: The length of LIS (longest increasing subsequence)
     */
    public int longestIncreasingSubsequence(int[] nums) {
        // write your code here
        if(nums.length==0){
			return 0;
		}
		int dp[]=new int[nums.length];
		for(int i=0;i<nums.length;i++){
			dp[i]=1;
			for(int j=0;j<i;j++){
				if(nums[i]>nums[j]&&dp[j]+1>dp[i])
					dp[i]=dp[j]+1;
			}
		}
		int max=Integer.MIN_VALUE;
		for(int i=0;i<nums.length;i++){
			max=Math.max(max, dp[i]);
		}
		return max;
    }
}


Published 254 original articles · won praise 23 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_30242987/article/details/104721054