Java递归求某个集合的所有子集组成的集合,即幂集

来源:互联网 发布:安卓版电子狗软件 编辑:程序博客网 时间:2024/06/05 02:23

方法很简单,递归。

package com.junoflo;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.util.ArrayList;import java.util.List;import java.util.Scanner;/** * Created by Administrator on 2017/7/21. */public class PowerSet {    public static void powerSet(int i, List<Integer> set, List<Integer> tmp){        if(i > set.size()){            tmp.forEach(o -> System.out.print(o + " "));            System.out.println();        }else {            int x = set.get(i-1);            tmp.add(x);            powerSet(i+1,set,tmp);            tmp.remove(Integer.valueOf(x));//直接用tmp.remove(x) 编译器会以为x是下标            powerSet(i+1,set,tmp);        }    }    public static void main(String[] args) throws FileNotFoundException {        File file = new File("C:\\Users\\Administrator\\Desktop","data");        FileInputStream fis = new FileInputStream(file);        System.setIn(fis);        Scanner in = new Scanner(System.in);        int size = in.nextInt();        List<Integer> originalSet = new ArrayList<>();        List<Integer> tmp = new ArrayList<>();        for(int i = 0; i < size; i++){            originalSet.add(in.nextInt());        }        powerSet(1,originalSet,tmp);    }}
原创粉丝点击