import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.time.StopWatch;
/*
* @(#)PermutationAndCombination.java 2010-3-23
*
* @COPYRIGHT@
*/
/**
* <p>
* 排列组合
* </p>
*
* @version 1.0
* @author Lancelot
*
*/
public class PermutationAndCombination {
private char[] resource = new char[0];
private List resultBuffer = new ArrayList();
public PermutationAndCombination() {}
public PermutationAndCombination(char[] resource) {
this.resource = resource;
}
public PermutationAndCombination(String resource) {
this.resource = resource.toCharArray();
}
public List process() {
for(int i = 0, num = resource.length; i < num; i++) {
char[] part = ArrayUtils.subarray(resource, i, i + 1);
char[] tmpResource = ArrayUtils.remove(resource, i);
permutation(tmpResource, part);
}
return resultBuffer;
}
private void permutation(char[] resource, char[] prefix) {
int num = resource.length;
if( 1 == num ) {
char[] result = ArrayUtils.addAll(prefix, resource);
System.out.println(String.valueOf(result));
//下面的代码可以解决重复结果的问题——比如传入了aaaa/ aaba这样的字符串,但效率会稍差。
/*String resultString = String.valueOf(result);
if( !resultBuffer.contains(resultString) ) {
resultBuffer.add(resultString);
}*/
} else {
for(int i = 0; i < num; i++) {
char[] result = ArrayUtils.add(prefix, resource[i]);
permutation(ArrayUtils.remove(resource, i), result);
}
}
}
public static void main(String[] args) {
StopWatch clock = new StopWatch();
clock.start();
System.out.println(new PermutationAndCombination("abcdefge").process());
clock.stop();
System.out.println("clock.getTime() => " + clock.getTime());
}
}
这段代码可在1.3/ 1.4的环境下运行,而且在效率与博主的代码相差无几的情况下,可读性要更好。
回复 更多评论