Generating all permutations of a given string

前端 未结 30 2131
我寻月下人不归
我寻月下人不归 2020-11-21 06:35

What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer st

30条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 06:46

    This is what I did through basic understanding of Permutations and Recursive function calling. Takes a bit of time but it's done independently.

    public class LexicographicPermutations {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s="abc";
        Listcombinations=new ArrayList();
        combinations=permutations(s);
        Collections.sort(combinations);
        System.out.println(combinations);
    }
    
    private static List permutations(String s) {
        // TODO Auto-generated method stub
        Listcombinations=new ArrayList();
        if(s.length()==1){
            combinations.add(s);
        }
        else{
            for(int i=0;itemp=permutations(s.substring(0, i)+s.substring(i+1));
                for (String string : temp) {
                    combinations.add(s.charAt(i)+string);
                }
            }
        }
        return combinations;
    }}
    

    which generates Output as [abc, acb, bac, bca, cab, cba].

    Basic logic behind it is

    For each character, consider it as 1st character & find the combinations of remaining characters. e.g. [abc](Combination of abc)->.

    1. a->[bc](a x Combination of (bc))->{abc,acb}
    2. b->[ac](b x Combination of (ac))->{bac,bca}
    3. c->[ab](c x Combination of (ab))->{cab,cba}

    And then recursively calling each [bc],[ac] & [ab] independently.

提交回复
热议问题