46. Permutations
给一个数组,返回其所有排列组合情况。
Input: [1,2,3]
Output:
[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
和前面回溯不一样的是,每个解的长度是固定的,在回溯时需要访问所有的元素,看哪个还没有使用,所以用了一个used数组来记录:
public List<List<Integer>> permute(int[] nums) {
boolean[] used = new boolean[nums.length];
for (boolean i : used)
i = false;
help(nums, 0, new ArrayList<>(), used);
return res;
}
List<List<Integer>> res = new ArrayList<>();
public void help(int[] nums, int index, List<Integer> one, boolean[] used) {
if (index == nums.length) {
res.add(new ArrayList<>(one));
} else {
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
one.add(nums[i]);
used[i] = true;
help(nums, index+1, one, used);
one.remove(one.size()-1);
used[i] = false;
}
}
}
47. Permutations II
和上面一题区别就是给的数组可能含有重复值。
所有代码也差不多,唯一的区别就是先排个序,然后每次回溯时跳过重复的元素:
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
boolean[] used = new boolean[nums.length];
for (boolean i : used)
i = false;
help(nums, 0, new ArrayList<>(), used);
return res;
}
List<List<Integer>> res = new ArrayList<>();
public void help(int[] nums, int index, List<Integer> one, boolean[] used) {
if (index == nums.length) {
res.add(new ArrayList<>(one));
} else {
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
one.add(nums[i]);
used[i] = true;
help(nums, index+1, one, used);
one.remove(one.size()-1);
used[i] = false;
//回溯时跳过重复元素
while (i+1 < nums.length && nums[i] == nums[i+1]) i++;
}
}
}
784. Letter Case Permutation
给一个字符串,包含数字和字母,返回所有字母大小写不同的可能的组合。
Examples:
Input: S = “a1b2”
Output: [“a1b2”, “a1B2”, “A1b2”, “A1B2”]
这题区别就大一些了,之前的都是选择不同的组合或者不同的排列,需要用到循环。但这题是对每个元素分别进行改变,看有多少种结果,不需要循环,但在遍历到符合条件的元素时还需要再次进行回溯:
public List<String> letterCasePermutation(String S) {
help(0, new StringBuffer(S));
return res;
}
List<String> res = new ArrayList<>();
public void help(int index, StringBuffer str) {
if (index == str.length()) {
res.add(new String(str.toString()));
} else {
help(index+1, str);
//非字母字符就不进行回溯了
if ((str.charAt(index) >= 'A' && str.charAt(index) <= 'Z') || (str.charAt(index) >= 'a' && str.charAt(index) <= 'z')) {
if (str.charAt(index) >= 'A' && str.charAt(index) <= 'Z') {
str.setCharAt(index, (char) (str.charAt(index) + 32));
} else if (str.charAt(index) >= 'a' && str.charAt(index) <= 'z') {
str.setCharAt(index, (char) (str.charAt(index) - 32));
}
help(index + 1, str);
}
}
}