673. Number of Longest Increasing Subsequence

LeetCode medium оригинал: C# #array #csharp #dynamic-programming #leetcode #medium #search

Дан массив целых чисел nums, верните количество самых длинных строго возрастающих подпоследовательностей.

Пример:

Input: n = 1, presses = 1

Output: 2

Explanation: Status can be:

- [off] by pressing button 1

- [on] by pressing button 2

C# решение

сопоставлено/оригинал
public class Solution {
    public int FindNumberOfLIS(int[] nums) {
        int n = nums.Length;
        int[] length = new int[n];
        int[] count = new int[n];
        Array.Fill(length, 1);
        Array.Fill(count, 1);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    if (length[j] + 1 > length[i]) {
                        length[i] = length[j] + 1;
                        count[i] = 0;
                    }
                    if (length[j] + 1 == length[i]) {
                        count[i] += count[j];
                    }
                }
            }
        }
        int maxLength = length.Max();
        int result = 0;
        for (int i = 0; i < n; i++) {
            if (length[i] == maxLength) {
                result += count[i];
            }
        }
        return result;
    }
}

C++ решение

auto-draft, проверить перед отправкой
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int FindNumberOfLIS(vector<int>& nums) {
        int n = nums.size();
        vector<int>& length = new int[n];
        vector<int>& count = new int[n];
        Array.Fill(length, 1);
        Array.Fill(count, 1);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    if (length[j] + 1 > length[i]) {
                        length[i] = length[j] + 1;
                        count[i] = 0;
                    }
                    if (length[j] + 1 == length[i]) {
                        count[i] += count[j];
                    }
                }
            }
        }
        int maxLength = length.Max();
        int result = 0;
        for (int i = 0; i < n; i++) {
            if (length[i] == maxLength) {
                result += count[i];
            }
        }
        return result;
    }
}

Java решение

сопоставлено/оригинал
class Solution {
    public int findNumberOfLIS(int[] nums) {
        int n = nums.length;
        int[] length = new int[n];
        int[] count = new int[n];
        Arrays.fill(length, 1);
        Arrays.fill(count, 1);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    if (length[j] + 1 > length[i]) {
                        length[i] = length[j] + 1;
                        count[i] = 0;
                    }
                    if (length[j] + 1 == length[i]) {
                        count[i] += count[j];
                    }
                }
            }
        }

        int maxLength = Arrays.stream(length).max().getAsInt();
        int result = 0;

        for (int i = 0; i < n; i++) {
            if (length[i] == maxLength) {
                result += count[i];
            }
        }

        return result;
    }
}

JavaScript решение

сопоставлено/оригинал
var findNumberOfLIS = function(nums) {
    let n = nums.length;
    let length = new Array(n).fill(1);
    let count = new Array(n).fill(1);

    for (let i = 0; i < n; i++) {
        for (let j = 0; j < i; j++) {
            if (nums[j] < nums[i]) {
                if (length[j] + 1 > length[i]) {
                    length[i] = length[j] + 1;
                    count[i] = 0;
                }
                if (length[j] + 1 === length[i]) {
                    count[i] += count[j];
                }
            }
        }
    }

    let maxLength = Math.max(...length);
    let result = 0;

    for (let i = 0; i < n; i++) {
        if (length[i] === maxLength) {
            result += count[i];
        }
    }

    return result;
}

Python решение

сопоставлено/оригинал
class Solution:
    def findNumberOfLIS(self, nums):
        n = len(nums)
        length = [1] * n
        count = [1] * n

        for i in range(n):
            for j in range(i):
                if nums[j] < nums[i]:
                    if length[j] + 1 > length[i]:
                        length[i] = length[j] + 1
                        count[i] = 0
                    if length[j] + 1 == length[i]:
                        count[i] += count[j]

        maxLength = max(length)
        result = 0

        for i in range(n):
            if length[i] == maxLength:
                result += count[i]

        return result

Go решение

сопоставлено/оригинал
func findNumberOfLIS(nums []int) int {
    n := len(nums)
    length := make([]int, n)
    count := make([]int, n)
    for i := range length {
        length[i] = 1
        count[i] = 1
    }

    for i := 0; i < n; i++ {
        for j := 0; j < i; j++ {
            if nums[j] < nums[i] {
                if length[j]+1 > length[i] {
                    length[i] = length[j] + 1
                    count[i] = 0
                }
                if length[j]+1 == length[i] {
                    count[i] += count[j]
                }
            }
        }
    }

    maxLength := 0
    for _, l := range length {
        if l > maxLength {
            maxLength = l
        }
    }

    result := 0
    for i := 0; i < n; i++ {
        if length[i] == maxLength {
            result += count[i]
        }
    }

    return result
}

Algorithm

Объявите два массива динамического программирования length и count, и инициализируйте их значениями length[i]=1 и count[i]=1. Итерируйте i от 0 до n−1. Для каждого i итерируйте j от 0 до i−1 и, если nums[j] < nums[i], обновите length[i] и count[i] в зависимости от значений length[j] и count[j].

Найдите максимальное значение в массиве length и сохраните его в переменной maxLength. Инициализируйте переменную result = 0.

Итерируйте i от 0 до n−1 и, если length[i] = maxLength, добавьте count[i] к result. Верните result.

😎

Вакансии для этой задачи

Показаны активные вакансии с пересечением по тегам задачи.

Все вакансии
Активных вакансий пока нет.