- 子集
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
class Solution {
LinkedList<Integer> tmp = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
if(nums.length == 0){
res.add(new ArrayList<>());
return res;
}
backcracking(nums, 0);
return res;
}
private void backcracking(int[] nums, int index){
res.add(new ArrayList<>(tmp));
if(index >= nums.length){
return;
}
for (int i = index; i < nums.length; i++){
tmp.add(nums[i]);
backcracking(nums, i + 1);
tmp.removeLast();
}
}
}
- 递增子序列
给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。
数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。
示例 1:
输入:nums = [4,6,7,7]
输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> tmp = new LinkedList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backcracking(nums, 0);
return res;
}
private void backcracking(int[] nums, int index){
if(tmp.size() >= 2){
res.add(new ArrayList<>(tmp));
}
if(index >= nums.length){
return;
}
boolean[] flag = new boolean[201];
for(int i = index; i < nums.length; i++){
if(!tmp.isEmpty() && nums[i] < tmp.get(tmp.size() - 1) || flag[nums[i] + 100]){
continue;
}
flag[nums[i] + 100] = true;
tmp.add(nums[i]);
backcracking(nums, i + 1);
tmp.removeLast();
}
}
}
46. 全排列
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例 1:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> tmp = new LinkedList<>();
boolean[] flag;
public List<List<Integer>> permute(int[] nums) {
if(nums.length == 0){
return res;
}
flag = new boolean[nums.length];
backcracking(nums);
return res;
}
private void backcracking(int[] nums){
if(tmp.size() == nums.length){
res.add(new ArrayList<>(tmp));
return;
}
for(int i = 0; i < nums.length; i++){
if(flag[i]) continue;
flag[i] = true;
tmp.add(nums[i]);
backcracking(nums);
tmp.removeLast();
flag[i] = false;
}
}
}
- 全排列 II
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> tmp = new LinkedList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
if(nums.length == 0){
return res;
}
boolean[] flag = new boolean[nums.length];
Arrays.sort(nums);
backcracking(nums, flag);
return res;
}
private void backcracking(int[] nums, boolean[] flag){
if(tmp.size() == nums.length){
res.add(new ArrayList<>(tmp));
return;
}
for(int i = 0; i < nums.length; i++){
if(i > 0 && !flag[i - 1] && nums[i] == nums[i -1]) continue;
if(!flag[i]){
flag[i] = true;
tmp.add(nums[i]);
backcracking(nums, flag);
tmp.removeLast();
flag[i] = false;
}
}
}
}