题目:
幂集。编写一种方法,返回某集合的所有子集。集合中不包含重复的元素。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
分析:
利用一个队列来保存子集,初始添加一个空集,遍历每一个元素,此时取队列中所有的子集,选择加入该元素或者不加入该元素,把生成的新的子集再全部加入到队列中,最后幂集就生成好了。
程序:
class Solution { public List<List<Integer>> subsets(int[] nums) { Queue<List<Integer>> queue = new LinkedList<>(); queue.offer(new ArrayList<>()); for(int i = 0; i < nums.length; ++i){ int len = queue.size(); for(int j = 0; j < len; ++j){ List<Integer> list = queue.poll(); queue.offer(new ArrayList<>(list)); list.add(nums[i]); queue.offer(list); } } return res = new ArrayList<>(queue); } private List<List<Integer>> res; }