java全排列通用工具类
2018-07-20 来源:open-open
全排列处理接口
public interface PermutationProcessor<T> {
void process(T[]array);
}
全排列类
public final class FullPermutation {
public static <T> void permutate(T a[], PermutationProcessor<T> processor) {
permutate(a, 0, a.length,processor);
}
static <T> void permutate(T a[], int m, int n,PermutationProcessor<T> processor) {
int i;
T t;
if (m < n - 1) {
permutate(a, m + 1, n,processor);
for (i = m + 1; i < n; i++) {
swap(a, m, i);
permutate(a, m + 1, n,processor);
swap(a, m, i);
}
} else {
processor.process(a);
}
}
private static <T> void swap(T[] a, int m, int i) {
T t;
t = a[m];
a[m] = a[i];
a[i] = t;
}
}
[代码]调用示例
public static void main(String[] args) {
Integer[] a={1,2,4};
FullPermutation.permutate(a, new PermutationProcessor<Integer>() {
@Override
public void process(Integer[] array) {
for(int i:array){
System.out.printf("%d ",i);
}
System.out.println();
}
});
}
[代码]运行结果
1 2 4 1 4 2 2 1 4 2 4 1 4 2 1 4 1 2
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐