全子集问题
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
if (nums == null) {
return results;
}
if (nums.length == 0) {
results.add(new ArrayList<Integer>());
return results;
}
Arrays.sort(nums);
helper(new ArrayList<Integer>(), nums, 0, results);
return results;
}
private void helper(ArrayList<Integer> subset,
int[] nums,
int startIndex,
List<List<Integer>> results) {
results.add(new ArrayList<Integer>(subset));
for (int i = startIndex; i < nums.length; i++) {
subset.add(nums[i]);
helper(subset, nums, i + 1, results);
subset.remove(subset.size() - 1);
}
}
}
带重复元素的全子集问题
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
Deque<Integer> subset = new ArrayDeque<>(nums.length);
dfs(nums, 0, subset, res);
return res;
}
private void dfs(int[] nums, int k, Deque<Integer> subset, List<List<Integer>> res) {
res.add(new ArrayList<>(subset));
for (int i = k; i < nums.length; ++i) {
if (i != k && nums[i] == nums[i - 1]){
continue;
}
subset.addLast(nums[i]);
dfs(nums, i + 1, subset, res);
subset.removeLast();
}
}
}
不带重复元素的排列问题
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
if (nums == null) {
return results;
}
dfs(nums, new boolean[nums.length], new ArrayList<Integer>(), results);
return results;
}
private void dfs(int[] nums,
boolean[] visited,
List<Integer> permutation,
List<List<Integer>> results) {
if (nums.length == permutation.size()) {
results.add(new ArrayList<Integer>(permutation));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i]) {
continue;
}
permutation.add(nums[i]);
visited[i] = true;
dfs(nums, visited, permutation, results);
visited[i] = false;
permutation.remove(permutation.size() - 1);
}
}
}
有重复元素的排列问题
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
if (nums == null) {
return results;
}
Arrays.sort(nums);
dfs(nums, new boolean[nums.length], new ArrayList<Integer>(), results);
return results;
}
private void dfs(int[] nums,
boolean[] visited,
List<Integer> permutation,
List<List<Integer>> results) {
if (nums.length == permutation.size()) {
results.add(new ArrayList<Integer>(permutation));
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;
}
permutation.add(nums[i]);
visited[i] = true;
dfs(nums, visited, permutation, results);
visited[i] = false;
permutation.remove(permutation.size() - 1);
}
}
}