zoukankan      html  css  js  c++  java
  • 集合的子集

    题目描述
    请编写一个方法,返回某集合的所有非空子集。

    给定一个int数组A和数组的大小int n,请返回A的所有非空子集。保证A的元素个数小于等于20,且元素互异。各子集内部从大到小排序,子集之间字典逆序排序,见样例。

    测试样例:
    [123,456,789]
    返回:{[789,456,123],[789,456],[789,123],[789],[456 123],[456],[123]}


    import java.util.*;

    public class Subset {
    ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> getSubsets(int[] A, int n) {
    // write code here
    getAllList(A, n-1, new ArrayList<Integer>());
    lists.remove(lists.size()-1);
    return lists;
    }

    private void getAllList(int[] A, int index, ArrayList<Integer> list) {
    if (index < 0) {
    lists.add(new ArrayList<Integer>(list));
    return;
    }
    list.add(A[index]);
    getAllList(A, index-1, list);
    list.remove(Integer.valueOf(A[index]));
    getAllList(A, index-1, list);
    }
    }

  • 相关阅读:
    组合与封装
    继承与派生
    面向对象编程
    subprocess、re、logging模块
    json、pickle、collections、openpyxl模块
    python内置模块
    递归函数与模块
    生成式、面向过程、与函数式
    叠加装饰器与迭代器
    闭包函数与装饰器
  • 原文地址:https://www.cnblogs.com/hyhy904/p/10958523.html
Copyright © 2011-2022 走看看