aur*_*ron 6 algorithm complexity-theory big-o permutation
我对算法分析非常熟悉,可以告诉Big-O我使用的大多数算法.但是我已经被困了几个小时无法想出我写的这段代码的Big-O.
基本上它是一种为字符串生成排列的方法.它的工作原理是将字符串中的每个字符作为第一个字符,并将其与子字符串的排列组合,减去该字符(递归).
如果我输入代码来计算迭代次数,我就得到O(N!)和O(N ^ N)之间的东西.但我无法弄清楚如何在心理上进行分析.任何建议都非常感谢!
import java.util.ArrayList;
import java.util.List;
public class Permutation {
int count = 0;
List<String> findPermutations(String str) {
List<String> permutations = new ArrayList<String>();
if (str.length() <= 1) {
count++;
permutations.add(str);
return permutations;
}
for (int i = 0; i < str.length(); i++) {
String sub = str.substring(0, i) + str.substring(i + 1);
for (String permOfSub : findPermutations(sub)) {
count++;
permutations.add(str.charAt(i) + permOfSub);
}
}
return permutations;
}
public static void main(String[] args) {
for (String s : new String[] {"a", "ab", "abc", "abcd", "abcde", "abcdef", "abcdefg", "abcdefgh"}) {
Permutation p = new Permutation();
p.findPermutations(s);
System.out.printf("Count %d vs N! %d%n", p.count, fact(s.length()));
}
}
private static int fact(int i) {
return i <= 1 ? i : i * fact(i-1);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑1:添加测试程序
编辑2:添加count++基本情况
递推方程:T(n) = n*(T(n-1) + (n-1)!), T(1) = 1其中n = str.length.
WolframAlfa 表示解为 n*(1) n即n*n!。
上面假设所有字符串操作都是 O(1)。String sub = ...否则,如果将和线路的成本permutations.add(str.charAt(i) + permOfSub)视为 O(n),则等式为:
T(n+1)=(n+1)*(n + T(n) + n!*(n+1))
Run Code Online (Sandbox Code Playgroud)
T(n) ~ (n*n+2*n-1)*n! IE,O(n!*n*n)