LeetCode-78 子集
题目链接:https://leetcode-cn.com/problems/subsets/
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3] 输出: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
reback(nums, result, new ArrayList<>(), 0);
return result;
}
// 方法一:回溯算法
public static void reback(int[] nums, List<List<Integer>> result, List<Integer> temp, int start) {
if (start == nums.length + 1) { // 可以自己理解一下,为什么是length + 1
return;
}
result.add(new ArrayList<>(temp));
for (int i = start, length = nums.length; i < length; i++) {
temp.add(nums[i]);
reback(nums, result, temp, i + 1);
temp.remove(temp.size() - 1);
}
}
// 方法二:遇到一个数就把所有子集加上该数,组成新的子集
public static List loop(int[] nums){
List<List<Integer>> list = new ArrayList<>();
if (nums.length == 0) {
return list;
}
// 遇到一个数就把所有子集加上该数组成新的子集,遍历完毕即是所有子集
list.add(new ArrayList<Integer>());
List<Integer> temp, newTemp;
ListIterator<List<Integer>> it;
for (int i : nums) {
// 遍历当前结果
it = list.listIterator();
while (it.hasNext()) {
temp = it.next();
// 在此基础之上添加一个元素
newTemp = new ArrayList<>(temp);
newTemp.add(i);
it.add(newTemp);
}
}
return list;
}
LeetCode-90 子集Ⅱ
题目链接:https://leetcode-cn.com/problems/subsets-ii/
给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: [1,2,2] 输出: [ [2], [1], [1,2,2], [2,2], [1,2], [] ]
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
reback(nums, result, new ArrayList<>(), 0);
return result;
}
// 回溯算法
public static void reback(int[] nums, List<List<Integer>> result, List<Integer> temp, int start) {
if (start == nums.length + 1) {
return;
}
result.add(new ArrayList<>(temp));
int lastUsed = Integer.MIN_VALUE;
for (int i = start, length = nums.length; i < length; i++) {
if (nums[i] != lastUsed) {// 去重:如果当前数与上次递归的数字相同,continue
temp.add(nums[i]);
reback(nums, result, temp, i + 1);
temp.remove(temp.size() - 1);
lastUsed = nums[i];
}
}
}