日期:2014-05-20  浏览次数:20615 次

数组中所有数字的(顺序不一样也是一种)任意组合
假设我现在有一个数组int a[3]={1,2,3},那么他的组合就有以下几种,
1:{1,2,3}
2:{1,3,2}
3:{2,1,3}
4:{2,3,1}
5:{3,1,2}
6:{3,2,1}
我想要4个数字,但是4个种类太多,就举个例子,希望大家帮想想
数组,组合,顺序

------解决方案--------------------
import java.util.ArrayList;
import java.util.List;

public class Test {

static List<int[]> allSorts = new ArrayList<int[]>();
    
    public static void permutation(int[] nums, int start, int end) {
        if (start == end) {
            int[] newNums = new int[nums.length]; 
            for (int i=0; i<=end; i++) {
                newNums[i] = nums[i];
            }
            allSorts.add(newNums); 
        } else {
            for (int i=start; i<=end; i++) {
                int temp = nums[start];
                nums[start] = nums[i];
                nums[i] = temp;
                permutation(nums, start + 1, end); 
                nums[i] = nums[start];
                nums[start] = temp;
            }
        }
    }
        
    public static void main(String[] args) {
        int[] numArray = {1, 2, 3, 4};
        permutation(numArray, 0, numArray.length - 1);
        int[][] a = new int[allSorts.size()][]; 
        allSorts.toArray(a);
            

        for (int i=0; i<a.length; i++) {
            int[] nums = a[i];
            for (int j=0; j<nums.length; j++) {