Permutation algorithm for array of integers in Java

前端 未结 9 2062
-上瘾入骨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:20

    By adding a TreeSet it removes duplicates and sorts the permutations.


    package permutations;
    
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.TreeSet;
    
    
    public class Permutations {
    
    
    public static void main(String args[])
    {
        Scanner scanner = new Scanner(new InputStreamReader(System.in));
        System.out.println("This application accepts input of a string and creates a list of all     possible permutations\n\r");
    
        System.out.println("Please Enter a string of characters");
        String input = scanner.nextLine();
    
        String[] elements = input.split("");
        Permutations g = new Permutations();
    
        ArrayList permutations = g.generatePermutations(elements);
    
        TreeSet ts = new TreeSet();
        for ( String s : permutations)
        {
            //System.out.println(s);
            ts.add(s);
        }
        System.out.println("List of all possible permutations");
        System.out.println(ts);
    
    }
    
    private ArrayList generatePermutations( String[] elements )
    {
        ArrayList permutations = new ArrayList();
        if ( elements.length == 2 )
        {
    
            String x1 = elements[0]  + elements[1]; 
            String x2 = elements[1]  + elements[0];  
            permutations.add(x1);
            permutations.add(x2);
    
        }
        else {
            for (  int i = 0 ; i < elements.length  ; i++)
            {
                String[] elements2 = new String[elements.length -1];
                int kalo = 0;
                for( int j =0 ; j< elements2.length ; j++ )
                {
                    if( i == j)
                    {
                        kalo = 1;
                    }
                    elements2[j] = elements[j+kalo];
                }
                ArrayList k2 = generatePermutations(elements2);
                for( String x : k2 )
                {
                    String s = elements[i]+x;
                    permutations.add(s);
                }
            }
        }
    
        return permutations;
        }
    }
    

提交回复
热议问题