【发布时间】:2016-04-06 21:39:49
【问题描述】:
我正在使用此代码 https://stackoverflow.com/a/4240323/2655623 创建排列并对每个结果进行一些计算。
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
int p = prefix.length();
if(p==5){
//do some calculation for |prefix| = 5
return;
}
for (int i = 0; i < n; i++){
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
这个算法对我很有效。但是,我想看看如何删除重复字符,这样我就不再计算前缀了。例如对于
permutation("aacccbbdeeeef");
我会处理abcde关于
A = 2 * 4*3*2*1 when a----
B = 2 * 4*3*2*1 when b----
C = 3 * 4*3*2*1 when c----
and so on...
// I hope you get the idea
我想知道我是否可以减少重复计算的数量。
我认为的一种方法是对字符顺序进行排序,当我对它们使用 FOR 时,只计算每个重复字符中的一个。
for (int i = 0; i < n; i++){
if(i>0 && str.charAt(i) == str.charAt(i-1)) continue;
permutation.....
}
这对我来说很好,因为只需要排列一次。当重复字母数量较多时,它会大大减少调用次数。
现在,总结一下,我想知道是否
- 这是保证我不会错过任何排列吗?
- 如何防止像 a(1)ba(2)cd 和 a(2)ba(1)cd 这样的情况 当 p=5 时发生。至于 p=8 或 10,我使用的技巧不会那么有效。那我需要做什么?
非常感谢。
【问题讨论】:
标签: java algorithm unique permutation