【发布时间】:2022-01-20 03:11:16
【问题描述】:
你能帮我理解下面的代码sn-p吗?注释说它正在通过回溯进行字符串排列,但我就是不明白。我不明白嵌套的 for 循环在做什么。我试图用“Cat”跟随代码。不是排列集有吗?
public static Set<String> getPermutations(String inputString) {
if(inputString.length() <= 1) {
return new HashSet<>(Collections.singletonList(inputString));
}
String allCharsExceptLast = inputString.substring(0, inputString.length()-1);
char lastChar = inputString.charAt(inputString.length()-1);
Set<String> permutationsOfAllCharsExceptLast = getPermutations(allCharsExceptLast);
Set<String> permutations = new HashSet<>();
for(String permutationOfAllCharsExceptLast: permutationsOfAllCharsExceptLast) {
for(int position = 0; position <= allCharsExceptLast.length(); position++) {
String permutation = permutationOfAllCharsExceptLast.substring(0, position) + lastChar +
permutationOfAllCharsExceptLast.substring(position);
permutations.add(permutation);
}
}
return permutations;
}
}
【问题讨论】:
标签: java algorithm data-structures backtracking