673. longest increasing sequence number

  • analysis
* 假设对于以 nums[i] 结尾的序列,我们知道最长序列的长度 length[i],以及具有该长度的序列的 count[i]。
* 对于每一个 j<i 和一个 nums[i]>nums[j],我们可以将一个 nums[i] 附加到以 nums[j] 结尾的最长子序列上。
* 如果这些序列的长度 length[j]+1 > length[i],那么我们就知道现在有count[j]个这种长度(length[j]+1)的序列。如果这些序列的长度length[j]+1 == length[i],那么我们就知道现在有 count[j] 个额外的序列(即 count[i]+=count[j]。

* The result is the sum of each count[i] while its corresponding length[i] is the maximum length.

public int findNumberOfLIS(int[] nums) {
        int[] length = new int[nums.length];
        int[] count = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            length[i] = 1;
            count[i] = 1;
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    if (length[j] + 1 > length[i]) {
                        length[i] = length[j] + 1;
                        count[i] = count[j];
                    } else if (length[j] + 1 == length[i]) {
                        count[i] += count[j];
                    }
                }
            }
        }

        int maxLen = 0;
        for (int len : length) {
            maxLen = Math.max(maxLen, len);
        }
        int result = 0;
        for (int i = 0; i < length.length; i++) {
            if (length[i] == maxLen) {
                result += count[i];
            }
        }
        return result;
    }

Guess you like

Origin www.cnblogs.com/lasclocker/p/11441998.html