动态规划——什么是渐近运行时?

发布于 2025-01-02 10:18:31 字数 1018 浏览 4 评论 0原文

我正在自学动态编程。这几乎是神奇的。但说真的。无论如何,我解决的问题是:给定一个有 N 级台阶的楼梯和一个可以一次走 1、2 或 3 步的孩子,孩子可以通过多少种不同的方式到达顶层?.问题不太难,我的实现如下。

import java.util.HashMap;

public class ChildSteps {
    private HashMap<Integer, Integer> waysToStep;

    public ChildSteps() {
        waysToStep = new HashMap<Integer, Integer>();
    }

    public int getNthStep(int n) {
        if (n < 0) return 0; // 0 ways to get to a negative step

        // Base Case
        if (n == 0) return 1;

        // If not yet memorized
        if (!waysToStep.containsKey(n)) {
            waysToStep.put(n, getNthStep(n - 3) + getNthStep(n - 2) + getNthStep(n - 1));
        }

        return waysToStep.get(n);
    }
}

但是,现在我想获取运行时。我该如何解决这个问题?我熟悉(但不多)Akra-Bazzi 和 Master Theorem。这些适用于此吗?

http://en.wikipedia.org/wiki/Master_theorem

这里看起来可能是: T(N) = 3 * T(???) + O(1) 但我真的不确定。

谢谢你们。

I'm teaching myself dynamic programming. It's almost magical. But seriously. Anyway, the problem I worked out was : Given a stairs of N steps and a child who can either take 1, 2, or 3 steps at a time, how many different ways can the child reach the top step?. The problem wasn't too hard, my implementation is below.

import java.util.HashMap;

public class ChildSteps {
    private HashMap<Integer, Integer> waysToStep;

    public ChildSteps() {
        waysToStep = new HashMap<Integer, Integer>();
    }

    public int getNthStep(int n) {
        if (n < 0) return 0; // 0 ways to get to a negative step

        // Base Case
        if (n == 0) return 1;

        // If not yet memorized
        if (!waysToStep.containsKey(n)) {
            waysToStep.put(n, getNthStep(n - 3) + getNthStep(n - 2) + getNthStep(n - 1));
        }

        return waysToStep.get(n);
    }
}

However, now I want to get the runtime. How should I figure this out? I am familiar (and not much more) with Akra-Bazzi and Master Theorem. Do those apply here?

http://en.wikipedia.org/wiki/Master_theorem

Here it would seem that it could be: T(N) = 3 * T(???) + O(1) but I'm really not sure.

thanks guys.

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

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

发布评论

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

评论(1

殤城〤 2025-01-09 10:18:31

在最坏的情况分析中,它会是:

T(N) = N * (containsKey(N) + 8)

假设 containsKey = N(可能是 N^2Log(N)),那么这将简化为 T (N) = N。

您必须找出 containsKey(N) 的函数才能得到实际的方程。

不过你真的想多了;您不需要为此进行算法分析。适合您的名言:“过早的优化是万恶之源”

In a worst case scenario analysis it would be:

T(N) = N * (containsKey(N) + 8)

Assuming that containsKey = N (it is probably N^2 or Log(N)) then this simplifies to T(N) = N.

You would have to find out the function for containsKey(N) to get the actual equation.

You're really over thinking this though; you don't need to do a algorithm analysis for this. Good quote for you: "Premature optimization is the root of all evil"

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