【发布时间】:2016-11-24 02:22:29
【问题描述】:
我试图弄清楚生成给定字符串的所有排列的代码的复杂性(来自Cracking the Coding Interview book)是O(n!)。
我知道这是我们所拥有的最好的复杂性!排列,但我想以代码方式理解它,因为并非每个执行此操作的算法都是 O(n!)。
代码:
import java.util.*;
public class QuestionA {
public static ArrayList<String> getPerms(String str) {
if (str == null) {
return null;
}
ArrayList<String> permutations = new ArrayList<String>();
if (str.length() == 0) { // base case
permutations.add("");
return permutations;
}
char first = str.charAt(0); // get the first character
String remainder = str.substring(1); // remove the first character
ArrayList<String> words = getPerms(remainder);
for (String word : words) {
for (int j = 0; j <= word.length(); j++) {
String s = insertCharAt(word, first, j);
permutations.add(s);
}
}
return permutations;
}
public static String insertCharAt(String word, char c, int i) {
String start = word.substring(0, i);
String end = word.substring(i);
return start + c + end;
}
public static void main(String[] args) {
ArrayList<String> list = getPerms("abcde");
System.out.println("There are " + list.size() + " permutations.");
for (String s : list) {
System.out.println(s);
}
}
}
这是我到目前为止的想法: 在任何函数调用中,可用的字数为 (n-1) ;假设我们处于余数长度为 (n-1) 的地方。现在为所有这些 (n-1) 个单词在所有可能的位置插入第 n 个元素需要 (n-1)*(n-1) 时间。
所以在整个执行过程中,应该是 (n-1)^2+(n-2)^2+(n-3)^2+....2^2+1^2 操作,我不要认为是 n!。
我错过了什么?
【问题讨论】:
-
我不知道我是否正确,但我认为它是 O((N+1)!) ?
标签: java algorithm time-complexity permutation