LIS 最长上升子序列的长度 LeetCode 300

package com.dp;
/**
** @author wanglj
** @time 2020-7-29 23:36:17
** @filecomment 
** @fileName Solution.java
** @packageName com.dp
** @Todo  LIS LC300 最长上升子序列的长度
**/
//i状态可以从在它之前比它小的数字状态转换过来
/*
 * 例如nums{2,3,5,1,6}
 * dp[0] = 1 {2}
 * dp[1] = max{dp[0]+1,0+1} = 2,{2,3}
 * dp[2] = max{dp[0]+1,dp[1]+1,1}  = 3; {2,3,5}
 * dp[3] = 1 {1}
 * dp[4] = max{dp[0]+1,dp[1]+1,dp[2]+1,dp[3]+1,1} = 4;{2,3,5,6}
 * res = max{dp[i]}
 * */
import java.util.Arrays;
public class Solution {
	public int lengthOfLIS(int[] nums) {
        if(nums.length==0){
            return 0;
        }
        int n = nums.length;
		int[] dp = new int[n+1];
		dp[0] = 1;
		Arrays.fill(dp, 1);
		for(int i = 1;i < n;i++) {
			for(int j = 0;j < i;j++) {
				if(nums[j]<nums[i]) {
					dp[i] = Math.max(dp[j]+1, dp[i]);
				}
				else {
					continue;
				}
			}
		}
		int res = dp[0];
		for(int i = 1;i < n;i++) {
			if(dp[i]>res) {
				res = dp[i];
			}
		}
		return res;
    }
}


//测试代码
package com.dp;

import java.util.Arrays;

//动态规划  最长上升子序列的长度
//LC 300 Longest Increasing Subsequence
/*
 Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4 
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 

 */
public class LIS {
	public void lengthOfLIS(int[] nums) {
		int n = nums.length;
		int[] dp = new int[n];
		dp[0] = 1;
		Arrays.fill(dp, 1);
		for(int i = 1;i < n;i++) {
			for(int j = 0;j < i;j++) {
				if(nums[j]<nums[i]) {
					dp[i] = Math.max(dp[j]+1, dp[i]);
				}
				else {
					continue;
				}
			}
		}
		int res = dp[0];
		for(int i = 1;i < n;i++) {
			if(dp[i]>res) {
				res = dp[i];
			}
			System.out.println(dp[i]);
		}
//		return res;
    }
	public static void main(String[] args) {
		LIS soLis = new LIS();
		int[] nums = new int[] {10,9,2,5,3,7,101,18} ;
//		System.out.println(soLis.lengthOfLIS(nums));
		soLis.lengthOfLIS(nums);
	}
}

 

 
 
 
 
 
 
 
 
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w͏l͏j͏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值