leetcode 300, 673 (longest increasing subsequence)

Solution for leetcode 300

https://leetcode.com/problems/longest-increasing-subsequence/

dp[i] represents the longest subsequence ending at position [i] so that nums[i] is included

The transition matrix is :  for all  j < i and nums[j] < nums[i], dp[i] can be updated as the maximum value between dp[i] (original value)  and dp[j] + 1 

notice that for code simplicity, in our code, dp[j] is 1 smaller than the actual value (we omit the step of initializing arr elements to 1 and choose to add 1 in the end instead)

class Solution {
    public int lengthOfLIS(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];
        int output = 0; 
        for(int i = 1; i < n; i++){
            for(int j = 0; j < i; j++){
                if(nums[j] < nums[i]){
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                    output = Math.max(output, dp[i]);
                }
            }
        }
        return output + 1; 
    }
}

Solution for leetcode 673

https://leetcode.com/problems/number-of-longest-increasing-subsequence/

class Solution {
    public int findNumberOfLIS(int[] nums) {
        int n = nums.length;
        //records the length of the lis upto index i
        int[] dp = new int[n];
        //records the number of the lis upto index i 
        int[] count = new int[n];
        int longestLength = 1;
        Arrays.fill(dp,1);
        //Don't forget this step
        Arrays.fill(count, 1);
        for(int i = 1; i < n; i++){
            for(int j = 0; j < i; j++){
                if(nums[i] > nums[j]){
                    if(dp[j] + 1  == dp[i]){
                        count[i] += count[j];
                    }
                    //cover what we have before because we find a longer length now
                    else if(dp[j] + 1 > dp[i]){
                        dp[i] = dp[j] + 1;
                        count[i] = count[j];
                        longestLength = Math.max(longestLength, dp[i]);
                        
                    }
                }
            }
        }
        //the lis can end at different positions
        int output = 0;
        for(int k = 0; k < n; k++){
            if(dp[k] == longestLength){
                output += count[k];  
            }
        }
        return output;  
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值