一、题目描述:
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
题目链接:https://leetcode-cn.com/problems/subsets/
二、解题思路:
抓住重点:1.所有元素互不相同;2.得到所有子集
就是个排列组合题,得到所有数组元素的所有组合,并print
难点:如何减少遍历,用最高效的方法得到结果;
思路:
逐个取数组中的元素,添加到已有结果的数组中,形成新数组,然后添加进结果数组;
1.遍历nums数组,得到每个元素,current = nums[i]
2.遍历所有结果数组 List<List> res_list ,等到结果数组中的每个元素 List resList = res_list[j]
3.将current添加到 每个resList 中,形成【新的数组】,即,resList.add(current)
4.将【新的数组】添加到 结果数组中
举个例子:
原始数组为:nums = [1,2,3]
结果数组为:res = [[]]
第一次遍历:
1.遍历 nums:
index = 0 ; current = nums[0] = 1; res = [[]]
2.遍历res:
第一次遍历 结果数组只有初始化时的空元素 = []
3.将current添加到空元素,形成【新的数组】 = [1]
4.将【新的数组】添加到 结果数组中,即得到结果数组= [[], [1]]
第二次遍历:
1.遍历 nums:
index = 1 ; current = nums[1] = 2; res = [[], [1]]
2.遍历res:
第二次遍历 结果数组有元素:[], [1]
3.将current添加到每个结果数组元素中,形成【新的数组】 = [2], [1,2]
4.将【新的数组】添加到 结果数组中,即得到结果数组= [[], [1], [2], [1,2]]
第三次遍历:
1.遍历 nums:
index = 2; current = nums[2] = 3; res = [[], [1], [2], [1,2]]
2.遍历res:
第三次遍历 结果数组有元素:[[], [1], [2], [1,2]]
3.将current添加到每个结果数组元素中,形成【新的数组】 = [3], [1, 3], [2, 3], [1, 2, 3]
4.将【新的数组】添加到 结果数组中,即得到结果数组= [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
以上为完整遍历过程,得到最终结果。
三、代码实现(java版本)
class Solution {
public List<List<Integer>> subsets(int[] nums) {
//init
List<List<Integer>> list = new ArrayList<>();
list.add(new ArrayList<>());
int len = nums.length;
for(int i = 0; i < len; i++) {
int m = list.size();
int current = nums[i];
for(int j = 0; j < m; j++) {
List<Integer> subList = list.get(j);
//copy list
List<Integer> newSubList = new ArrayList(subList);
newSubList.add(current);
list.add(newSubList);
}
}
return list;
}
}
执行结果:
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:41.2 MB, 在所有 Java 提交中击败了60.49%的用户```