生成最小和最大字符数之间给定字符集的所有排列的列表

时间:2016-03-14 21:48:20

标签: java string algorithm permutation

我正在尝试生成一个列表,列出Java中指定的最小和最大字符数之间给定字符集的所有排列,以便在密码破解程序中使用。例如,字符集ab,最小字符数为2,最大字符数为4,这将是输出:

aa
ab
ba
bb
aaa
aab
aba
baa
abb
bab
bba
bbb
aaaa
aaab
aaba
abaa
baaa
aabb
abab
baab
abbb
babb
bbbb
bbba
bbab
baba
bbaa
abba

我很难过,无法想办法有效地做到这一点,没有重复。如果字符集为String,最小字符数为int,最大字符数为int,那么执行此操作的最佳递归算法是什么?

这是我想要做的伪代码:

//1.start at the minimum number of characters with all characters at index 0
//2.increment rightmost by 1 until last char is reached
//3.shift left by 1
//4.increment this char by 1 unless last char is reached
//5.repeat step 2
//6.repeat step 3
//7.repeat step 4; if last char is reached repeat step 3
//8.when you can't shift left anymore go to the next number of characters, unless the maximum has been reached

我需要做的就是弄清楚如何将其转换为递归方法。

1 个答案:

答案 0 :(得分:1)

最直接的版本是对每个字母使用单个递归调用,跟踪深度。然后对从min到max的每个长度进行递归调用:

char[] letterBank;
// Read in the chars and separate them into a char array

List<String> myList = new ArrayList<>();

void populateMyList(int depth, String stringSoFar) {
  if (depth == 0) {
    myList.add(stringSoFar)
    return;
  }
  for (int i = 0; i < letterBank.length; i++) {
    populateMyList(depth - 1, stringSoFar + letterBank[i]);
  }
}

main() {
  for(int i = min; i <= max; i++)
    populateMyList(i, "");
}

请注意,如果您想要效率,请使用StringBuilder而不是字符串作为参数。