【发布时间】:2014-02-27 18:49:11
【问题描述】:
考虑元素唯一性问题,其中给定一个范围 i, i + 1, 。 . . , j, 数组 A 的索引,我们想要确定此范围内的元素 A[i], A[i+1], . . . , A[j], 都是唯一的,即这组数组条目中没有重复的元素。考虑以下(低效的)递归算法。
public static boolean isUnique(int[] A, int start, int end) {
if (start >= end) return true; // the range is too small for repeats
// check recursively if first part of array A is unique
if (!isUnique(A,start,end-1) // there is duplicate in A[start],...,A[end-1]
return false;
// check recursively if second part of array A is unique
if (!isUnique(A,start+1,end) // there is duplicate in A[start+1],...,A[end]
return false;
return (A[start] != A[end]; // check if first and last are different
}
令 n 表示所考虑的条目数,即,令 n = end - start + 1。对于大 n,此代码片段的渐近运行时间的上限是多少?提供简短而准确的解释。 (如果你不解释,你会失去分数。)在开始你的解释之前,你可以说有多少递归调用 算法将在它终止之前进行,并分析每次调用该算法的操作数。 或者,您可以提供表征该算法运行时间的递归,然后求解 使用迭代替换技术?
这个问题来自算法课的示例练习考试,这是我目前的答案,请有人帮忙验证我是否在正确的轨道上
答案:
递推方程:
T(n) = 1 如果 n = 1, T(n) = 2T(n-1) 如果 n > 1
在使用迭代替换解决后,我得到了
2^k * T (n-k) 我将其解决为 O(2^(n-1)) 并将其简化为 O(2^n)
【问题讨论】:
标签: algorithm complexity-theory time-complexity recurrence