Generate list of all possible permutations of a string

后端 未结 30 2960
故里飘歌
故里飘歌 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:36

    Some working Java code based on Sarp's answer:

    public class permute {
    
        static void permute(int level, String permuted,
                        boolean used[], String original) {
            int length = original.length();
            if (level == length) {
                System.out.println(permuted);
            } else {
                for (int i = 0; i < length; i++) {
                    if (!used[i]) {
                        used[i] = true;
                        permute(level + 1, permuted + original.charAt(i),
                           used, original);
                        used[i] = false;
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            String s = "hello";
            boolean used[] = {false, false, false, false, false};
            permute(0, "", used, s);
        }
    }
    

提交回复
热议问题