# 回溯算法实战系列之全排列问题

·  阅读 252

784. 字母大小写全排列

• S 的长度不超过12。
• S 仅由数字和字母组成。

### 代码实战Ⅰ

``````class Solution {
StringBuilder path = new StringBuilder();
public List<String> letterCasePermutation(String s) {
ArrayList<String> res = new ArrayList<>();
backTracking(s, res, 0);
return res;
}

public void backTracking(String s, ArrayList<String> res, int index) {
if (path.length() == s.length()) {
return;
}

for (int i = index; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
path.append(ch);
backTracking(s, res, i + 1);
path.deleteCharAt(path.length() - 1);
} else {
path.append(Character.toLowerCase(ch));
backTracking(s, res, i + 1);
path.deleteCharAt(path.length() - 1);

path.append(Character.toUpperCase(ch));
backTracking(s, res, i + 1);
path.deleteCharAt(path.length() - 1);
}
}
}
}

### 题目实例Ⅱ

47. 全排列 II

[[1,1,2],

[1,2,1],

[2,1,1]]

• 1 <= nums.length <= 8
• -10 <= nums[i] <= 10

### 代码实战Ⅱ

``````class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
int depth = 0;
Arrays.sort(nums);
boolean[] used = new boolean[nums.length];
backTracking(nums, used, path, depth, res);
return res;
}

public static void backTracking(int[] nums, boolean[] used, LinkedList<Integer> path, int depth, List<List<Integer>> res) {
if (nums.length == depth) {
return;
}
for (int i = 0; i < nums.length; i++) {
if (!used[i]) {
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
continue;
}
used[i] = true;
backTracking(nums, used, path, depth + 1, res);
used[i] = false;
path.removeLast();
}
}
}
}