Smart way to generate permutation and combination of String

前端 未结 7 455
耶瑟儿~
耶瑟儿~ 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:07

    i came across this question as one of the interview question. Following is the solution that i have implemented for this problem using recursion.

    public class PasswordCracker {
    
    private List doComputations(String inputString) {
    
        List totalList =  new ArrayList();
        for (int i = 1; i <= inputString.length(); i++) {
    
            totalList.addAll(getCombinationsPerLength(inputString, i));
        }
        return totalList;
    
    }
    
    private ArrayList getCombinationsPerLength(
            String inputString, int i) {
    
        ArrayList combinations = new ArrayList();
    
        if (i == 1) {
    
            char [] charArray = inputString.toCharArray();
            for (int j = 0; j < charArray.length; j++) {
                combinations.add(((Character)charArray[j]).toString());
            }
            return combinations;
        }
        for (int j = 0; j < inputString.length(); j++) {
    
            ArrayList combs = getCombinationsPerLength(inputString, i-1);
            for (String string : combs) {
                combinations.add(inputString.charAt(j) + string);
            }
        }
    
        return combinations;
    }
    public static void main(String args[]) {
    
        String testString = "abc";
        PasswordCracker crackerTest = new PasswordCracker();
        System.out.println(crackerTest.doComputations(testString));
    
    }
    }
    

提交回复
热议问题