【发布时间】:2021-08-30 23:46:21
【问题描述】:
我在 GeekforGeeks https://www.geeksforgeeks.org/minimum-number-of-jumps-to-reach-end-of-a-given-array/ 中检查“到达终点的最小跳跃次数”问题。 我对那里提到的时间复杂度感到困惑,即 O(n^n)。
// Returns minimum number of
// jumps to reach arr[h] from arr[l]
static int minJumps(int arr[], int l, int h)
{
// Base case: when source
// and destination are same
if (h == l)
return 0;
// When nothing is reachable
// from the given source
if (arr[l] == 0)
return Integer.MAX_VALUE;
// Traverse through all the points
// reachable from arr[l]. Recursively
// get the minimum number of jumps
// needed to reach arr[h] from these
// reachable points.
int min = Integer.MAX_VALUE;
for (int i = l + 1; i <= h
&& i <= l + arr[l];
i++) {
int jumps = minJumps(arr, i, h);
if (jumps != Integer.MAX_VALUE && jumps + 1 < min)
min = jumps + 1;
}
return min;
}
如果我看到上面的代码块,就会从 i=l+1 调用 minJumps(arr, i, h) 递归调用。所以在每一个递归步骤中,l(start position)都会增加1。时间复杂度应该如下计算。
T(N) = (n-1)*(n-2)*(n-3)...*1
= (n-1)!
我不明白为什么时间复杂度是 O(n^n)。在其他几个地方,我也看到这个递归解决方案的时间复杂度被称为 O(n^n) 没有适当的解释。请帮我做一个简单的解释并指出我在这里遗漏的内容。
【问题讨论】:
-
当 2 不在等式中时,您如何将其分解?
-
我认为是 O((n-1)! ) 但你是对的。该网站的复杂性有点草率——它是 O(n^n) 并没有错,因为大 O 是一个上限,但这不是一个严格的界限。
-
我不明白你为什么要乘以每个值。
-
对我来说好像
O(2^n)。不过不确定。 -
@Shantanu 我现在对方程式进行了更正。
标签: java arrays algorithm time-complexity