[英]DFS to find all permutations of subsets
Given a string with no duplicate characters, return a list with all permutations of the string and all its subsets.给定一个没有重复字符的字符串,返回一个包含该字符串及其所有子集的所有排列的列表。
Examples例子
Set = "abc"
, all permutations are: ["", "a", "ab", "abc", "ac", "acb", "b", "ba", "bac", "bc", "bca", "c", "cb", "cba", "ca", "cab"]
. Set = "abc"
,所有排列为: ["", "a", "ab", "abc", "ac", "acb", "b", "ba", "bac", "bc", "bca", "c", "cb", "cba", "ca", "cab"]
。
I know how to do it if I broke up the whole thing into two parts:如果我把整个事情分成两部分,我知道该怎么做:
But I am wondering if there is a way to write the DFS helper function to do it in just one step.但我想知道是否有一种方法可以编写 DFS 辅助函数,只需一步即可完成。
Sure.当然。 This isn't the fastest method, but it's simple and enumerates in the lexicographic order such that the input string is the minimum permutation.
这不是最快的方法,但它很简单,并按字典顺序枚举,以便输入字符串是最小排列。
private static void printPerms(char[] set, int i) {
System.out.println(new String(set, 0, i));
for (int j = i; j < set.length; j++) {
char c = set[j];
// move c to position i
for (int k = j; k > i; k--) {
set[k] = set[k - 1];
}
set[i] = c;
printPerms(set, i + 1);
// move c back to position j
for (int k = i; k < j; k++) {
set[k] = set[k + 1];
}
set[j] = c;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.