动态规划——什么是渐近运行时?
我正在自学动态编程。这几乎是神奇的。但说真的。无论如何,我解决的问题是:给定一个有 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在最坏的情况分析中,它会是:
假设 containsKey = N(可能是
N^2
或Log(N)
),那么这将简化为T (N) = N。
您必须找出
containsKey(N)
的函数才能得到实际的方程。不过你真的想多了;您不需要为此进行算法分析。适合您的名言:“过早的优化是万恶之源”
In a worst case scenario analysis it would be:
Assuming that containsKey = N (it is probably
N^2
orLog(N)
) then this simplifies toT(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"