输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例:
输入:s = "abc"
输出:["abc","acb","bac","bca","cab","cba"]
限制:
1 <= s 的长度 <= 8
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/zi-fu-chuan-de-pai-lie-lcof/
思路:回溯算法
java 代码:
class Solution {
public String[] permutation(String s) {
Set<String> result = new HashSet<>();
backtrack(s,new LinkedList<>(),result);
String[] array = new String[result.size()];
int i = 0;
for(String ss:result) {
array[i++] = ss;
}
return array;
}
public void backtrack(String s,List<Integer> subList,Set<String> result) {
if (subList.size() == s.length()) {
StringBuilder stringBuilder = new StringBuilder();
for(int index:subList) {
stringBuilder.append(s.charAt(index));
}
result.add(stringBuilder.toString());
return;
}
for(int i=0;i<s.length();i++) {
if (subList.contains(i)) {
continue;
}
subList.add(i);
backtrack(s,subList,result);
subList.remove(subList.size()-1);
}
}
}