这也适用于空字符串或 n == 0。
重载是第二种重载combination()
方法(采用四个参数的方法)。第一个重载只是将输入字符串转换为 aList<Character>
并准备一个空的哈希集来存储结果:
Set<String> combination(String input, int n) {
List<Character> letters = new ArrayList<Character>();
for (int i = 0; i < input.length(); ++i)
letters.add(input.charAt(i));
Set<String> results = new HashSet<String>();
combination("", letters, n, results);
return results;
}
void combination(String soFar, List<Character> letters, int n,
Set<String> results) {
if (n == 0) {
results.add(soFar);
return;
}
int startIndex = soFar.length();
if (startIndex >= letters.size())
return;
for (int i = startIndex; i < letters.size(); ++i) {
// ch is the next candidate to add to the result that we're
// building (soFar)
char ch = letters.get(i);
// Swap the characters at positions i and position startIndex.
char temp = letters.get(startIndex);
letters.set(i, temp);
letters.set(startIndex, ch);
// add ch to soFar, compute combinations of length n-1.
// as startIndex is essentially soFar.length() this means that
// the recursive call will only process the remainder of the list.
combination(soFar + ch, letters, n - 1, result);
// Swap the characters back - restore the original state.
letters.set(i, ch);
letters.set(startIndex, temp);
}