【第十一周】673. Number of Longest Increasing Subsequence

原题

Given an unsorted array of integers, find the number of longest increasing subsequence. 

Example 1:
Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.
Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int.

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

解题思路

这是一道基于LIS的问题:LIS只需要找出最长上升序列的长度,本问题需要找出的是最长上升序列的个数,即有多少长度相同且最长的上升序列。
所以主要算法依旧是LIS的动态规划,定义状态F(k)为前k个数的最长上升序列长度,状态转移方程为F(k+1) = max( F(i)+1 ) (当num[k+1]>num[i]) 。不过在LIS的基础上,我们还需要记录一个值:对于每一个F(i),都有一个Count[i],用于记录以num[i]结尾的最长上升子序列长度为F(i)的序列个数。也许我表述的很绕,Count[i]的作用就是统计各状态LIS的个数;在算法执行结束后,我们从所有F(i)中选择一个最大值max,在Count[i]中将所有F(i)为max的个数累计起来,就是所求的结果。

代码

class Solution {
public:
    int length[2000];
    int count[2000];
    int findNumberOfLIS(vector<int>& nums) {
        if (nums.size() == 0) return 0;
        for (int i:length) i = 0;
        for (int i:count) i = 0;
        length[0] = 1;
        count[0] = 1;
        int n = nums.size();
        for (int i = 0; i < n; i++) findLIS(nums, i);
        int ret = 0, Len = 0;
        for (int i = 0; i < n; i++) {
            if (length[i] > Len) {
                Len = length[i];
                ret = count[i];
            } else if (length[i] == Len) {
                ret += count[i];
            }
        }
        return ret;
    }
    void findLIS(vector<int>& nums, int n) {
        if (length[n] != 0) return;
        int curLen = 1;
        int number = 1;
        for (int i = 0; i < n; i++) {
            if (nums[n] > nums[i]) {
                int x = length[i] + 1;
                if (x > curLen) {
                    curLen = x;
                    number = count[i];
                } else if (x == curLen) {
                    number += count[i];
                }
            }
        }
        length[n] = curLen;
        count[n] = number;
    }

};

总结

1、要熟悉动态规划的经典问题,在原型上进行思路分析。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值