<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">今天做任务需要使用到数字的排列组合,是无重复数的排列,这一点得强调一下,网上看了一些其他童鞋们的算法,有比我条件苛刻的,我本来是想用javascript实现的,有些麻烦,就自己用java实现了一个基本的无重复数的排列,希望参考我的童鞋可以拿走自己改改适应你的需求,先把代码贴出来:</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre name="code" class="java">public class MainTest {
public static void main(String[] args) {
List<Integer> a = new ArrayList<Integer>(4);
a.add(1);
a.add(2);
a.add(3);
a.add(4);
a.add(5);
List<List<Integer>> resList = cal(a);
for (List<Integer> intList : resList) {
for (Integer i : intList) {
System.out.print(i + ", ");
}
System.out.println();
}
}
public static List<List<Integer>> cal(List<Integer> a) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
int size = a.size();
List<Integer> temp = null;
if(size == 2) {
temp = new ArrayList<Integer>(2);
temp.add(a.get(0));
temp.add(a.get(1));
res.add(temp);
temp = new ArrayList<Integer>(2);
temp.add(a.get(1));
temp.add(a.get(0));
res.add(temp);
} else if(size > 2) {
List<List<Integer>> tempRes = null;
Integer firstNum = null;
List<Integer> tempPar = null;
for(int i=0; i<size; i++) {
firstNum = a.get(i);
tempPar = new ArrayList<Integer>(a);
tempPar.remove(i);
tempRes = cal(tempPar);
if(tempRes != null && tempRes.size() > 0) {
for (List<Integer> intList : tempRes) {
intList.add(0, firstNum);
res.add(intList);
}
}
}
}
return res;
}
}
使用的是递归思想,模拟人类手动排序的步骤,每次一从剩余的数组中拿一个,剩余的再进行剩余数组的排列,直到最终只有两个数组,交换位置产生两个排列返回,然后层层递归回去求得解