/* Return permutation of [0, n) in a String array, for example
when n=3, it should return:
012
021
102
120
201
210
the order does not matter
*/
答案 0 :(得分:-1)
我在this site找到的一个解决方案:围绕它构建程序并添加你喜欢的数组。
package test;
import java.util.ArrayList;
public class Permutation {
public static void main(String[] args) {
for(ArrayList<Integer> al: permute(new int[]{1,2,3})){
for(Integer i : al){
System.out.print( i);
}
System.out.println(" ");
}
}
public static ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
permute(num, 0, result);
return result;
}
public static void permute(int[] num, int start, ArrayList<ArrayList<Integer>> result) {
if (start >= num.length) {
ArrayList<Integer> item = convertArrayToList(num);
result.add(item);
}
for (int j = start; j <= num.length - 1; j++) {
swap(num, start, j);
permute(num, start + 1, result);
swap(num, start, j);
}
}
private static ArrayList<Integer> convertArrayToList(int[] num) {
ArrayList<Integer> item = new ArrayList<Integer>();
for (int h = 0; h < num.length; h++) {
item.add(num[h]);
}
return item;
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}