[英]the time and space complexity of this permutation algorithm
我已經寫了這個排列算法。 你能幫我理解它的時間和空間復雜性嗎?
public static List<String> permutation(String str) {
List<String> result = new ArrayList<>();
if (str.length() == 1) {
result.add(str);
return result;
} else {
for (char c : str.toCharArray()) {
List<String> subPermList = permutation(str.replace(c + "", ""));
for (String substr : subPermList) {
result.add(c + substr);
}
}
return result;
}
}
我將只關注這個答案的時間復雜度。 首先是寫下T(n)
的遞推關系:
T(n) = n + // str.toCharArray()
n * // for (char c ...)
(
T(n-1) + // permutation(...)
n + // str.replace(...)
(n-1)! * n // for (String substr ...)
)
= n*T(n-1) + n*n! + n² + n
這種遞歸關系的解是Θ(n² * n!)
。
...這明顯比Θ(n * n!)
差,您可以在最佳實現中獲得所有排列的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.