解释求解“最长递增子序列”的算法问题

发布于 2024-12-02 10:28:48 字数 402 浏览 5 评论 0原文

过去两个小时我一直试图理解这个算法,但似乎无法理解。有人可以用简单易懂的方式解释一下吗?

function lis_length(a)
    n := a.length
    q := new Array(n)
    for k from 0 to n:
        max := 0;
        for j from 0 to k, if a[k] > a[j]:
            if q[j] > max, then set max = q[j].
        q[k] := max + 1;
    max := 0
    for i from 0 to n:
        if q[i] > max, then set max = q[i].
    return max;

I have been trying to understand this algorithm for past two hours, but can't seem to get it. Can someone please explain it in easy to understand manner?

function lis_length(a)
    n := a.length
    q := new Array(n)
    for k from 0 to n:
        max := 0;
        for j from 0 to k, if a[k] > a[j]:
            if q[j] > max, then set max = q[j].
        q[k] := max + 1;
    max := 0
    for i from 0 to n:
        if q[i] > max, then set max = q[i].
    return max;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

硬不硬你别怂 2024-12-09 10:28:48

第一个(双)循环终止后,q[i] 是在位置 i 处结束的最长递增子序列的长度。

要了解双循环的工作原理,假设 q[j] 已包含以 j 位置结束的最大递增子序列的长度,但仅限于 j在0k-1之间。鉴于此,您将如何计算q[k]

好吧,您会找到所有 jj k 和 a[j] a[k],查看相应的 q[j] 值中哪个最大,加一,然后将该值存储在 q[k] 中。这正是内循环的作用。

因此,在进入内部循环时,q[j] 已经具有 0k-1 之间的正确 j 值。并且在退出时,它还具有正确的 k 值。因此,当双循环退出时,q[i] 具有 0n 之间所有 i 的正确值代码>.

最后的循环只选择其中最大的一个,这就是答案。

After the first (double) loop terminates, q[i] is the length of the longest increasing subsequence ending at position i.

To see how the double loop works, suppose q[j] already contained the length of the largest increasing subsequence ending at position j, but only for j between 0 and k-1. Given this, how would you compute q[k]?

Well, you would find all of the j with j < k and a[j] < a[k], see which of the corresponding q[j] values was biggest, add one, and stash that value in q[k]. This is exactly what the inner loop does.

So at entry to the inner loop, q[j] already has the correct values for j between 0 and k-1. And at exit, it also has the correct value for k. So by the time the double loop exits, q[i] has the correct value for all i between 0 and n.

The final loop just selects the largest of those, which is the answer.

人疚 2024-12-09 10:28:48

对于每个元素,设置由当前元素构成的元素的最长子序列的计数,增加当前元素之前的元素的最长子序列的一个长度,使得它们的最大值小于当前元素的值。

该算法采用正数数组(元素不能为零或更少)。

For each element set the count of longest subsequence of elements made with current element as incremented by one length of longest subsequence of elements preceding current element such that their largest value is smaller than the value of current element.

The algorithm takes array of positive numbers (can't have zero or less as element).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文