Smart way to generate permutation and combination of String

前端 未结 7 450
耶瑟儿~
耶瑟儿~ 2021-02-01 22:37
String database[] = {\'a\', \'b\', \'c\'};

I would like to generate the following strings sequence, based on given database.



        
7条回答
  •  -上瘾入骨i
    2021-02-01 23:12

    You should check this answer: Getting every possible permutation of a string or combination including repeated characters in Java

    To get this code:

    public static String[] getAllLists(String[] elements, int lengthOfList)
    {
    
        //lists of length 1 are just the original elements
        if(lengthOfList == 1) return elements; 
        else {
            //initialize our returned list with the number of elements calculated above
            String[] allLists = new String[(int)Math.pow(elements.length, lengthOfList)];
    
            //the recursion--get all lists of length 3, length 2, all the way up to 1
            String[] allSublists = getAllLists(elements, lengthOfList - 1);
    
            //append the sublists to each element
            int arrayIndex = 0;
    
            for(int i = 0; i < elements.length; i++){
                for(int j = 0; j < allSublists.length; j++){
                    //add the newly appended combination to the list
                    allLists[arrayIndex] = elements[i] + allSublists[j];
                    arrayIndex++;
                }
            }
            return allLists;
        }
    }
    
    public static void main(String[] args){
        String[] database = {"a","b","c"};
        for(int i=1; i<=database.length; i++){
            String[] result = getAllLists(database, i);
            for(int j=0; j

    Although further improvement in memory could be made, since this solution generates all solution to memory first (the array), before we can print it. But the idea is the same, which is to use recursive algorithm.

提交回复
热议问题