673. Number of Longest Increasing Subsequence

1 题目理解

Given an integer array nums, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
输入:整数数组int[] nums
输出:最长递增子序列的个数
规则:子序列是指从原数组中找出若干元素组成新的数组。这些元素不一定是下标相邻的,但是元素前后顺序不能变。递增子序列就是新的子数组中,i>j,a[i]>=a[j]。

2 动态规划

我们用dp[i]来记录以第i个元素为结尾的最长递增子序列的长度。
那么设j=0,1,2…i-1,当nums[i]>nums[j]的时候,dp[j]+1就是一个可能的值。从这些值中取最大值,就是dp[i]的值。

dp[i]=max(dp[j]+1),0<=j<i && nums[i]>nums[j]

同时我们用count[i]记录以nums[i]为结尾的最长递增子序列有多少个。
例如nums=[1,3,5,4,7];
处理第0个元素1:dp[0]=1,count[0]=1
处理第1个元素3:3>1,dp[1]=2,count[1]=count[0]=1
处理第2个元素5:5>1,dp[2]=2,count[2]=count[0]=1
5>3,dp[1]+1>dp[2],所以更新dp[2]=3,count[2]=count[1]=1

所以当遇到dp[j]+1>dp[i]的时候,count[i]=count[j],当遇到dp[j]+1==dp[i]的时候,count[i] +=count[j]。做叠加。

class Solution {
    public int findNumberOfLIS(int[] nums) {
        if(nums==null || nums.length == 0) return 0;
        int n = nums.length;
        int[] dp = new int[n];
        int[] count = new int[n];
        Arrays.fill(count,1);
        dp[0] = 1;
        int max = dp[0];
        for(int i=1;i<n;i++){
            dp[i] = 1;
            for(int j=i-1;j>=0;j--){
                if(nums[i]>nums[j]){
                    if(dp[j]+1==dp[i]){
                        count[i] +=count[j];
                    }else if(dp[j]+1>dp[i]){
                        count[i] = count[j];
                        dp[i] = dp[j]+1;
                    }
                }
            }
            max = Math.max(dp[i],max);
        }
        int c = 0;
        
        for(int i=0;i<n;i++){
            if(dp[i]==max){
                c +=count[i];
            }
        }
        return c;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值