zoukankan      html  css  js  c++  java
  • LeetCode Subsets

    Given a set of distinct integers, S, 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 S = [1,2,3], a solution is:

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

    思路是,每次添加一个元素,就是在上一次的基础上,对每个列表加入元素,再与上一次的合并。

     1 public class Solution {
     2     public List<List<Integer>> subsets(int[] S) {
     3             List<List<Integer>> lastList=new ArrayList<>();
     4             List<Integer> nonSet= new ArrayList<>();
     5             lastList.add(nonSet);
     6             if (S==null || S.length==0) {
     7             return lastList;
     8             }
     9             Arrays.sort(S);
    10             
    11             for (int i = 0; i < S.length; i++) {
    12                 List<List<Integer>> tempList=new ArrayList<>();         
    13             for (List<Integer> list : lastList) {
    14                     List<Integer> currlist=new ArrayList<>();
    15                     currlist.addAll(list);
    16                     currlist.add(S[i]);
    17                     tempList.add(currlist);
    18             }
    19             lastList.addAll(tempList);
    20             }
    21             return lastList;
    22     }
    23 }
  • 相关阅读:
    Python运算符及逻辑运算
    Python编码、流程控制、格式化输出
    Docker私有仓库Harbor部署与使用
    react
    理事会
    关于elementui form表单过长,看不到未填项
    js
    vue 父子传值
    养生
    html知识点
  • 原文地址:https://www.cnblogs.com/birdhack/p/4055511.html
Copyright © 2011-2022 走看看