zoukankan      html  css  js  c++  java
  • Subsets *

    Given a set of distinct integers, nums, return all possible subsets.

    Note:

    • Elements in a subset must be in non-descending order.
    • 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],
      []
    ]



    算法思路:例如{1,2}的全部子集为{}{1}{2}{1,2}不妨假设为s1,加入3之后即{1,2,3}的全部子集该如何得到呢?简单一点方法就是将3依次加入{1,2}的子集当中得到新的子集{3}{1,3}{2,3}{1,2,3}设为s2,
    s1∩s2即为{1,2,3}的全部子集。


    public class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> re = new ArrayList<List<Integer>>();
            re.add(new ArrayList<Integer>());//初始化,加入空集
            Arrays.sort(nums);
            for(int i:nums) {
                List<List<Integer>> tmp = new ArrayList<List<Integer>>();
                for(List<Integer> set:re) {
                    List<Integer> tmp_set = new ArrayList<Integer>();
                    tmp_set.addAll(set);//clone原来存在的list
                    tmp_set.add(i);
                    tmp.add(tmp_set);
                }
                re.addAll(tmp);
            }
            return re;
        }
    }
  • 相关阅读:
    面向对象---2
    面向对象---1
    数组的复制、反转、查找(线性查找,二分法查找)
    Oracle 开放端口供客户机连接
    ORACLE常用函数大全
    ORACLE常用脚本
    C#开发实用知识点总结
    线程对话框基类
    C#开发常见问题处理
    通过修改注册表实现IE设置
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4476989.html
Copyright © 2011-2022 走看看