4647784
Posted 保护眼睛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了4647784相关的知识,希望对你有一定的参考价值。
dfs + 剪枝
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;
}
}
}
以上是关于4647784的主要内容,如果未能解决你的问题,请参考以下文章