【问题标题】:Return permutation of [0, n) in a String array,public static String[] printPermutation(int n)返回字符串数组中 [0, n) 的排列,public static String[] printPermutation(int n)
【发布时间】:2015-07-24 10:33:39
【问题描述】:
/* 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
         */

【问题讨论】:

    标签: java algorithm


    【解决方案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;
            }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-15
      • 2016-04-16
      • 1970-01-01
      • 2012-04-28
      • 2023-03-06
      • 1970-01-01
      • 2023-02-22
      • 2016-01-09
      相关资源
      最近更新 更多