Permutation algorithm for array of integers in Java

前端 未结 9 2070
-上瘾入骨i
-上瘾入骨i 2020-11-29 12:56

I have a working example to generate all char permutations in a String as below:

static ArrayList permutations(String s) {
        if (s == nul         


        
9条回答
  •  囚心锁ツ
    2020-11-29 13:27

    Here you go, the below sample code uses the recursive method to get the permutation. It is generic and you can specify the output location as you like. One bonus is you can specify delimiter as well.

    import java.io.FileNotFoundException;
    import java.io.OutputStream;
    import java.io.PrintStream;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class Permutation {
        //The entry of the permutation method
        public static  List permute(T[] arr){
            List result = new ArrayList();
            permute(new ArrayList(), Arrays.asList(arr), result);
            return result;
        }
    
        //This is the actual method doing the permutation
        private static  void permute(List pre, List cur, List out){
            int size = cur.size();
    
            if(size == 0){
                out.add((T[])pre.toArray());
            } else {
                for(int i=0; i tmpPre = new ArrayList(pre);
                    List tmpCur = new ArrayList(cur);
                    tmpPre.add(cur.get(i));
                    tmpCur.remove((T)cur.get(i));
    
                    permute(tmpPre, tmpCur, out);       
                }
            }
        }
    
        //Print each row of the permutated values
        private static  void print(List list, OutputStream out, char delim){
            try{
                for(T[] i : list){
                    int count = 0;
                    for(T t : i){
                        if(++count == i.length){
                            out.write((t.toString()).getBytes());
                        } else{
                            out.write((t.toString()+delim).getBytes());
                        }
                    }
                    out.write("\n".getBytes());
                }
            } catch (Exception ex){
                ex.printStackTrace();
            }
        }
    
        public static void main(String[] args) throws FileNotFoundException {
            Integer[] ints = new Integer[] {1, 2, 3, 4};
            Permutation.print(Permutation.permute(ints), System.out, ',');
    
            Character[] chars = {'a', 'b', 'c', 'd', 'e'};
            Permutation.print(Permutation.permute(chars), new PrintStream("permute.txt"), ' ');
    
            String[] strs = {"abc", "123"};
            Permutation.print(Permutation.permute(strs), System.err, ' ');
        }
    }
    

提交回复
热议问题