784. 字母大小写全排列
class Solution47 {
public static void main(String[] args) {
permuteUnique(new int[]{1, 2, 3});
res.forEach(System.out::println);
}
static List<List<Integer>> res = new LinkedList<>();
public static List<List<Integer>> permuteUnique(int[] nums) {
LinkedList<Integer> cur = new LinkedList<>();
boolean[] visited = new boolean[nums.length];
Arrays.sort(nums);
dfs(nums, res, cur, visited, 0);
return res;
}
public static void dfs(int[] nums, List<List<Integer>> res, LinkedList<Integer> cur, boolean[] visited, int index) {
if (cur.size() == nums.length) {
res.add(new ArrayList<>(cur));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i]) {
continue;
}
if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
continue;
}
cur.add(nums[i]);
visited[i] = true;
dfs(nums, res, cur, visited, index + 1);
cur.removeLast();
visited[i] = false;
}
}
}
46.全排列
class Solution083 {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> cur = new ArrayList<>();
boolean[] visited = new boolean[nums.length];
dfs(nums, res, cur, visited);
return res;
}
public void dfs(int[] nums, List<List<Integer>> res, List<Integer> cur, boolean[] visited) {
if (nums.length == cur.size()) {
res.add(new ArrayList<>(cur));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i]) continue;
cur.add(nums[i]);
visited[i] = true;
dfs(nums, res, cur, visited);
cur.remove(cur.size() - 1);
visited[i] = false;
}
}
}
47.全排列II
class Solution47 {
public static void main(String[] args) {
permuteUnique(new int[]{1, 2, 3});
res.forEach(System.out::println);
}
static List<List<Integer>> res = new LinkedList<>();
public static List<List<Integer>> permuteUnique(int[] nums) {
LinkedList<Integer> cur = new LinkedList<>();
boolean[] visited = new boolean[nums.length];
Arrays.sort(nums);
dfs(nums, res, cur, visited, 0);
return res;
}
public static void dfs(int[] nums, List<List<Integer>> res, LinkedList<Integer> cur, boolean[] visited, int index) {
if (cur.size() == nums.length) {
res.add(new ArrayList<>(cur));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i]) {
continue;
}
if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
continue;
}
cur.add(nums[i]);
visited[i] = true;
dfs(nums, res, cur, visited, index + 1);
cur.removeLast();
visited[i] = false;
}
}
}
|