Permutation algorithm for array of integers in Java

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

    This code takes String elements, but can me modified to work for integers:

    import java.util.*;
    /**
     * Write a description of class GeneratePermutations here.
     * 
     * @author Kushtrim 
     * @version 1.01
     */
    public class GeneratePermutations
    
    {
        public static void main(String args[])
        {
            GeneratePermutations g = new GeneratePermutations();
            String[] elements = {"a","b","c",};
            ArrayList permutations = g.generatePermutations(elements);
    
            for ( String s : permutations)
            {
                System.out.println(s);
            }
            //System.out.println(permutations.get(999999));
        }
    
        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;
        }
    }
    

提交回复
热议问题