`

Get all subset of a set

 
阅读更多

原创转载请注明出处:http://agilestyle.iteye.com/blog/2360659

 

找出一个Set集合中的所有子集

比如全集为 {1, 2, 3}

子集则有{},{1},{2},{3},{1,2},{1,3},{2,3},{1,2,3}

 

此算法的核心思想:递归

package org.fool.java.collections;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class GetAllSubSetTest {
    public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(3);
        set.add(4);

        // set to array
        Integer[] nums = set.toArray(new Integer[set.size()]);
        // use lambda to transform Integer[] to int[]
        printSubSet(Arrays.stream(nums).mapToInt(i -> i).toArray());
    }

    // step 1: decide how many elements in a sub-set to be printed
    public static void printSubSet(int[] nums) {
        for (int i = 0; i <= nums.length; i++) {
            boolean[] ifPrint = new boolean[nums.length];
            printSubSet(nums, ifPrint, 0, i);   // start from 0th index, and the size varies for the loop
        }
    }

    // step 2: Recursively process elements from left to right to print out all possible combination of elements with fixed size
    // we need three additional variables to keep track of status
    // boolean array to know whether printed out or not
    // start is the start index to be printed to prevent duplicates
    // remain is keeping track of how many remaining elements to be processed for the subset action
    public static void printSubSet(int[] nums, boolean[] ifPrint, int start, int remain) {
        // firstly if remain == 0, we done!
        if (remain == 0) {
            System.out.print("{");
            // check each ifPrint status to decide print or not
            for (int i = 0; i < ifPrint.length; i++) {
                if (ifPrint[i]) {
                    System.out.print(nums[i] + ", ");
                }
            }

            System.out.print("}\n");
        } else {
            // we need process char by char from the start position until end
            // before that, we need determine whether we proceed or not to check if (start + remain > nums.length)
            if (start + remain > nums.length) {

            } else {
                for (int i = start; i < nums.length; i++) {
                    // now before we come to recursive part we have to make sure this position is not used
                    if (!ifPrint[i]) {
                        // now assign its value to true as used indicator
                        ifPrint[i] = true;
                        // recursive call
                        printSubSet(nums, ifPrint, i + 1, remain - 1);
                        // set the position back to false and proceed from next element
                        ifPrint[i] = false;
                    }
                }
            }
        }
    }
}

Console Output


 

Reference

https://www.youtube.com/watch?v=wVNV3JEcikA 

 

  • 大小: 19.7 KB
分享到:
评论

相关推荐

    A subset of the STL10 Dataset (stlSubset.zip)

    You can just combine the intensities from all the color channels for the pixels into one long vector, as if you were working with a grayscale image with 3x the number of pixels as the original image.

    A Laymans Guide to a Subset of ASN 1 BER and DER

    ### ASN.1、BER与DER基础知识详解 #### 引言 随着软件开发复杂度的不断提高,抽象成为管理软件设计过程中的关键原则之一。通过抽象,设计师可以在不关心具体实现细节的情况下定义系统的一部分,从而简化了整体的...

    Instruction Set Reference_intel 64

    It provides detailed information about the instructions from A to M, which is a subset of the entire instruction set available for these architectures. #### Detailed Explanation of Key Knowledge ...

    is-subset-of:is-subset-of验证数组还是对象是子集

    is-subset-of验证数组还是对象是子集。 状态 类别 状态 版本 依存关系 开发依赖 建造 执照 安装 $ npm install is-subset-of 快速开始 首先,您需要在应用程序中添加对is-subset-of的引用: const { isSubsetOf...

    mnist数字识别数据库

    It is a subset of a larger set available from NIST. The digits have been size-normalized and centered in a fixed-size image. It is a good database for people who want to try learning techniques and ...

    SubSetSum_return_求最小子集和_

    Use an approximate algorithm to find the sum of subsets. S is a set of positive integers. Find a subset of S whose sum should be as large as possible but cannot exceed t

    论文研究-The studies of a peculiar subset of $\omega$.pdf

    关于 $\omega$ 的一个奇特子集的研究,赵峰,,根据 $\mbox{\upshape{ZF}}$ 公理,存在极限序数 $\omega$ 的一个奇特子集 $\bar{\omega}$,它既是无穷的,又是D\,–有穷的。只要 $\mbox{\upshape{ZF}}$ 公理�

    MNIST 手写数字图像数据集

    It is a subset of a larger set available from NIST. The digits have been size-normalized and centered in a fixed-size image. It is a good database for people who want to try learning techniques and ...

    Netflix Prize 完整数据集

    Netflix also identified a probe subset of 1,408,395 ratings within the training data set. The probe, quiz, and test data sets were chosen to have similar statistical properties. In summary, the data...

    论文研究-A second proof of the conjecture that the class P is a proper subset of the class NP.pdf

    对类P是类NP的真子集猜测的第二证明,徐万东,,判定一个任意的无向可平面图G是否是哈密顿图问题是六个重要的NP完全问题之一(HC)。本文根据判定除马图以外的任意无向图是否是哈密��

    SUBSET-037 v320.pdf

    标题和描述中提到的“SUBSET-037 v3.2.0 欧洲无线电系统功能接口规范”是指针对欧洲铁路交通管理系统(ERTMS)中的一个子集版本(Subset-037)的技术文件,这个版本是第3.2.0版,它详细规定了无线电系统的功能接口。...

    SSD7 选择题。Multiple-Choice

    The degree of a table is the number of _____ in the table. (a) keys (b) columns (c) rows (d) foreign keys Correct answer is (b) Your score on this question is: 10.00 Feedback: (b) ...

    Elements of Programming Interviews C++版

    EPI includes a study guide with several scenarios, ranging from weekend Hackathon to semester long preparation with a recommended a subset of problems for each scenario. All problems are classified...

    SUBSET-026-2 v300.pdf

    subset-026欧洲ETCS列车控制系统功能需求规格说明书,第二部分-基本系统描述,v3.0.0版本

    离散数学双语专业词汇表set集合subset子集elementmember.pdf

    "complement of B with respect to A"是A相对于B的补集,即B中不在A内的所有元素的集合。"symmetric difference"是两个集合中互不相同元素的集合。 "commutative"、"associative"和"distributive"描述了运算的性质...

    SUBSET-036_v241.pdf

    - **SUBSET-036_v241.pdf**:该文档标题指出这是一份编号为SUBSET-036的版本2.4.1的技术文件。 #### 描述解析 - **标识了点式应答器的技术条件**:描述明确指出该文档定义了点式应答器(即固定式地面信号装置)的...

    Elements of Programming Interview

    EPI includes a study guide with several scenarios, ranging from weekend Hackathon to semester long preparation with a recommended a subset of problems for each scenario. All problems are classified...

    THE MNIST DATABASE of handwritten digits

    It is a subset of a larger set available from NIST. The digits have been size-normalized and centered in a fixed-size image. It is a good database for people who want to try learning techniques and ...

    automatically maintaining wrappers for semi-structured web sources

    A substantial subset of the web data follows some kind of underlying structure. Nevertheless, HTML does not contain any schema or semantic information about the data it represents. A program able to ...

Global site tag (gtag.js) - Google Analytics