1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
| """ 回溯+剪枝 private void dfs(int[] nums, int len, int depth, boolean[] used, Deque<Integer> path, List<List<Integer>> res) int[] nums:输入的待排列数组 int len:最终终止时数组长度 int depth:目前数组的长度 boolean[] used:记录哪些数字被使用过 使用过true 没使用过false path:记录已选的数字 res:记录全部结果 """ import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.List;
public class Solution { public List<List<Integer>> permuteUnique(int[] nums) { int len = nums.length; List<List<Integer>> res = new ArrayList<>(); if (len == 0) { return res; } Arrays.sort(nums); boolean[] used = new boolean[len]; Deque<Integer> path = new ArrayDeque<>(len); dfs(nums, len, 0, used, path, res); return res; }
private void dfs(int[] nums, int len, int depth, boolean[] used, Deque<Integer> path, List<List<Integer>> res) { if (depth == len) { res.add(new ArrayList<>(path)); return; } for (int i = 0; i < len; ++i) { if (used[i]) { continue; } if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) { continue; } path.addLast(nums[i]); used[i] = true; dfs(nums, len, depth + 1, used, path, res); used[i] = false; path.removeLast(); } } }
### 剑指 Offer 38 字符串的全排列 #### 一、问题描述 ![题目描述](剑指offer/38.png) #### 二、具体代码 ```Java """ 回溯+剪枝 """ import java.util.ArrayList; import java.util.Arrays; import java.util.List;
public class Solution { public String[] permutation(String s) { int len = s.length(); if (len == 0) { return new String[0]; } char[] charArr = s.toCharArray(); Arrays.sort(charArr); StringBuilder path = new StringBuilder(); boolean[] used = new boolean[len];
List<String> res = new ArrayList<>(); dfs(charArr, len, 0, used, path, res);
return res.toArray(new String[0]); }
private void dfs(char[] charArr, int len, int depth, boolean[] used, StringBuilder path, List<String> res) { if (depth == len) { res.add(path.toString()); return; } for (int i = 0; i < len; i++) { if (!used[i]) { if (i > 0 && charArr[i] == charArr[i - 1] && !used[i - 1]) { continue; } used[i] = true; path.append(charArr[i]);
dfs(charArr, len, depth + 1, used, path, res);
path.deleteCharAt(path.length() - 1); used[i] = false; } } } }
|