zoukankan      html  css  js  c++  java
  • subsets(子集)

    Given a set of distinct integers, nums, return all possible subsets (the power set).

    Note: The solution set must not contain duplicate subsets.

    For example,
    If nums = [1,2,3], a solution is:

    [
      [3],
      [1],
      [2],
      [1,2,3],
      [1,3],
      [2,3],
      [1,2],
      []
    ]

    求给定数组的元素的子集。

    这题跟组合combination、全排列都有点像。列举所有情况,所以可以使用回溯。

    因为没有重复元素,所以不需要排列。

    依次遍历,并从后面的元素中继续选择作为集合元素。

    条件是:只要集合list中的元素长度小于等于数组长度,就添加,表示满足要求,是一个子集。

    代码如下:

    class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> res=new ArrayList<List<Integer>>();
            if(nums==null||nums.length==0) return res;
            helper(res,new ArrayList<Integer>(),nums,0);
            return res;
        }
        
        public void helper(List<List<Integer>> res,List<Integer> list,int[] nums,int index){
            if(list.size()<=nums.length){
                res.add(new ArrayList<Integer>(list));
            }
            for(int i=index;i<nums.length;i++){
                list.add(nums[i]);
                helper(res,list,nums,i+1);
                list.remove(list.size()-1);
            }
        }
    }
  • 相关阅读:
    jq元素拖拽
    路径中取文件名
    HBase相关问题
    HBase数据模型
    HBase安装过程
    HBase物理模型
    Hadoop性能调优
    Hive性能调优
    Hadoop资源调度器
    Hive的执行生命周期
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8182755.html
Copyright © 2011-2022 走看看