public class PermutationTest {
static List<String> list = new ArrayList<>();
public static void main(String[] args) {
String s = "abcd";
List<List<Character>> lists = new PermutationTest().PermutationV3(s.toCharArray());
for (List<Character> chars : lists) {
System.out.println(chars);
}
}
public void PermutationV1(char chs[], int start) {
if (start == chs.length) {
list.add(new String(chs));
}
for (int i = start; i <= chs.length - 1; i++) {
if (i == start || chs[i] != chs[start]) {
Swap(chs, i, start);
PermutationV1(chs, start + 1);
Swap(chs, i, start);
}
}
}
private void PermutationV2(char[] chars, int begin, int end) {
if (begin == end) {
list.add(new String(chars));
return;
}
for (int i = begin; i <= end; i++) {
if (!IsSwap(chars, begin, i)) {
continue;
}
Swap(chars, begin, i);
PermutationV2(chars, begin + 1, end);
Swap(chars, begin, i);
}
}
public List<List<Character>> PermutationV3(char[] chars) {
int len = chars.length;
List<List<Character>> res = new ArrayList<>();
if (len == 0) {
return res;
}
boolean[] used = new boolean[len];
List<Character> path = new ArrayList<>();
dfs(chars, len, 0, path, used, res);
return res;
}
private boolean IsSwap(char[] chars, int begin, int end) {
for (int j = begin; j < end; j++) {
if (chars[j] == chars[end]) {
return false;
}
}
return true;
}
private void dfs(char[] chars, int len, int depth,
List<Character> path, boolean[] used,
List<List<Character>> res) {
if (depth == len) {
res.add(new ArrayList<Character>(path));
return;
}
for (int i = 0; i < len; i++) {
if (!used[i]) {
path.add(chars[i]);
used[i] = true;
dfs(chars, len, depth + 1, path, used, res);
used[i] = false;
path.remove(path.size() - 1);
}
}
}
public void Swap(char chs[], int i, int j) {
char temp;
temp = chs[i];
chs[i] = chs[j];
chs[j] = temp;
}
}