zoukankan      html  css  js  c++  java
  • 程序员面试金典-面试题 08.04. 幂集

    题目:

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

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

    示例:

    输入: 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;
    }
  • 相关阅读:
    删除排序链表中的重复元素
    爬楼梯
    Sqrt(x)
    Add Binary
    fremarker导出word list
    url中文参数乱码问题
    取值范围
    动态添加echarts
    格式化数据保留两位小数,输入格式为 :xxx,xx,,,,x,,(x为浮点数)
    使用poi读取Excel文件数据
  • 原文地址:https://www.cnblogs.com/silentteller/p/12455562.html
Copyright © 2011-2022 走看看