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],
      []
    ]

    Solution:

     1 public class Subsets {
     2     public List<List<Integer>> subsets(int[] S) {
     3         List<List<Integer>> ret = new ArrayList<List<Integer>>();
     4         List<Integer> path = new ArrayList<Integer>();
     5         
     6         Arrays.sort(S);
     7         
     8         subsets(S, path, ret, 0);
     9         
    10         return ret;
    11     }
    12     
    13     public void subsets(int[] S, List<Integer> path, List<List<Integer>> ret, int index) {
    14         // 把当前的结果可以添加到结果集中. 空集也算是一种集合 
    15         ret.add(new ArrayList<Integer>(path));
    16         
    17         for (int i = index; i < S.length; i++) {
    18             path.add(S[i]);
    19             
    20             // 注意!这里的index要填写i + 1,而不是index,开始老是会犯错。
    21             subsets(S, path, ret, i + 1);
    22             path.remove(path.size() - 1);
    23         }
    24     }
    25 }
  • 相关阅读:
    flask 第三方组件
    Flask基础与进阶
    odoo10 视图
    odoo10 ORM操作
    odoo10基础
    字典的setdefault方法
    redis常用操作
    git常用命令与操作
    vue_axios
    odoo 权限设置
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4094055.html
Copyright © 2011-2022 走看看