Smart way to generate permutation and combination of String

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

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



        
7条回答
  •  再見小時候
    2021-02-01 23:27

    Ok, so the best solution to permutations is recursion. Say you had n different letters in the string. That would produce n sub problems, one for each set of permutations starting with each unique letter. Create a method permutationsWithPrefix(String thePrefix, String theString) which will solve these individual problems. Create another method listPermutations(String theString) a implementation would be something like

    void permutationsWithPrefix(String thePrefix, String theString) {
       if ( !theString.length ) println(thePrefix + theString);
       for(int i = 0; i < theString.length; i ++ ) {
          char c = theString.charAt(i);
          String workingOn = theString.subString(0, i) + theString.subString(i+1);   
          permutationsWithPrefix(prefix + c, workingOn);
       }
    } 
    
    void listPermutations(String theString) {
       permutationsWithPrefix("", theString);
    }
    

提交回复
热议问题