我试图找出的代码复杂度(从破解编码面试书),用于产生一个给定的字符串的所有排列如何为O的排列(N!)。复杂生成的字符串
我知道这是最好的复杂性,因为我们有n!排列,但我想了解它codewise,因为不是每个算法,这将是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点的操作,这我不认为是!
我在这里错过了什么?
我不知道我是对的,但我认为它是O((N + 1)!)? – shole