【发布时间】:2012-10-12 20:23:28
【问题描述】:
以下算法(伪代码)的时间复杂度是多少?我很难分析它。它是在另一个线程中指定的问题的实现:Algorithm to find max cost path of length N in matrix, from [0,0] to last row。但是因为我是新来的,所以我没有足够的积分在线程中发表评论(我认为)?这是我的第一篇文章,如果我做错了什么,请原谅。
该算法使用带有cache[][][][] 的记忆。在初始化期间cache[][][][] 填充为 -1。
使用maxPath(0,0,m,DOWN) 调用该方法。其中 m 是要走的步数,n
function maxPath(i, j, fuel, direction)
if i = n OR j = n OR j < 0 OR fuel = 0 then
return 0;
end if
if cache[i][j][f-1][d] != -1 then
return cache[i][j][f - 1][d];
end if
ret := 0
acc+ = matrix[i][j]
ret:=max(ret,maxPath(i+1, j, fuel-1, DOWN))
if f > n - i then . If there is enough steps to move horizontally
if d = RIGHT or d = DOWN then
ret:=max(ret,maxPath(i, j+1, fuel-1, RIGHT))
end if
if d = LEFT or d = DOWN then
ret:=max(ret,maxPath(i, j-1, fuel-1, LEFT))
end if
end if
return cache[i,j,fuel-1,direction] = ret + matrix[i][j]
end function
【问题讨论】:
-
燃料?收成?这不适合 Farmville 机器人,是吗?
-
如果我们不使用 memoization 显然是 O(3^n)
-
@Desolator 是的,我明白了。然而,随着记忆的时间复杂性降低,但我不确定多少。
-
@Marc B,感谢您指出这些事情,我已经编辑了我的帖子以使其更加通用。 (不适用于farmville)
-
通过记忆化,我用 wolfram-alpha 做了很多测试,确实看到递归调用的数量随着 O(mn^2) 的增加而增加。其中 m=nn^p 其中 0
标签: algorithm time-complexity dynamic-programming