Generate list of all possible permutations of a string

后端 未结 30 2846
故里飘歌
故里飘歌 2020-11-22 15:10

How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.

Any l

30条回答
  •  执笔经年
    2020-11-22 15:18

    The following Java recursion prints all permutations of a given string:

    //call it as permut("",str);
    
    public void permut(String str1,String str2){
        if(str2.length() != 0){
            char ch = str2.charAt(0);
            for(int i = 0; i <= str1.length();i++)
                permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),
                         str2.substring(1,str2.length()));
        }else{
        System.out.println(str1);
        }
    }
    

    Following is the updated version of above "permut" method which makes n! (n factorial) less recursive calls compared to the above method

    //call it as permut("",str);
    
    public void permut(String str1,String str2){
       if(str2.length() > 1){
           char ch = str2.charAt(0);
           for(int i = 0; i <= str1.length();i++)
              permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),
                     str2.substring(1,str2.length()));
       }else{
        char ch = str2.charAt(0);
        for(int i = 0; i <= str1.length();i++)
            System.out.println(str1.substring(0,i) + ch +    str1.substring(i,str1.length()),
                     str2.substring(1,str2.length()));
       }
    }
    

提交回复
热议问题