   力扣题解 
- HashSet 基于 HashMap 来实现的,是一个不允许有重复元素的集合。
- String.valueOf(char c) : 将 char 变量 c 转换成字符串
- Java 集合类中的 Set.contains() 方法判断 Set 集合是否包含指定的对象。该方法返回值为 boolean 类型,如果 Set 集合包含指定的对象,则返回 true,否则返回 false。
- ArrayList提供了一个将List转为数组的一个非常方便的方法toArray
class Solution {
List<String> res = new LinkedList<>();
char[] c;
public String[] permutation(String s) {
c = s.toCharArray();
dfs(0);
return res.toArray(new String[res.size()]);
}
void dfs(int x) {
if(x == c.length - 1) {
res.add(String.valueOf(c));
return;
}
HashSet<Character> set = new HashSet<>();
for(int i = x; i < c.length; i++) {
if(set.contains(c[i])) continue;
set.add(c[i]);
swap(i, x);
dfs(x + 1);
swap(i, x);
}
}
void swap(int a, int b) {
char tmp = c[a];
c[a] = c[b];
c[b] = tmp;
}
}
|