首页 > 其他 > 详细

程序员面试金典-面试题 08.04. 幂集

时间:2020-03-10 15:53:36      阅读:70      评论:0      收藏:0      [点我收藏+]

题目:

幂集。编写一种方法,返回某集合的所有子集。集合中不包含重复的元素。

说明:解集不能包含重复的子集。

示例:

输入: 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;
}

 

程序员面试金典-面试题 08.04. 幂集

原文:https://www.cnblogs.com/silentteller/p/12455562.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!