题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串 abc,则打印出由字符 a,b,c 所能排列出来的所有字符串 abc,acb,bac,bca,cab和cba
f
题目链接:https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
解题思路
- 递归法(回溯)
- 迭代法(字典生成)[后续更新]
import java.util.ArrayList;
import java.util.Collections;
public class Solution {
public ArrayList<String> Permutation(String str) {
ArrayList<String> result = new ArrayList<>();
rec(str.toCharArray(), 0, result);
Collections.sort(result);
return result;
}
private void rec(char[] chr, int i, ArrayList<String> result) {
if (i == chr.length - 1) {
String value = String.valueOf(chr);
if (!result.contains(value)) {
result.add(value);
}
} else {
for (int j = i; j < chr.length; j++) {
swap(i, j, chr);
rec(chr, i+1, result);
swap(i, j, chr);
}
}
}
private void swap(int i, int j, char[] chr) {
char tmp = chr[i];
chr[i] = chr[j];
chr[j] = tmp;
}
}