集册 Java实例教程 列出所有组合

列出所有组合

欢马劈雪     最近更新时间:2020-01-02 10:19:05

611
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
列出所有组合


//package com.nowjava;

import java.util.ArrayList;
/**
来 自 时   代    Java - nowjava.com
**/

import java.util.Arrays;

import java.util.HashSet;

import java.util.List;

import java.util.Set;


public class Main {

    public static void main(String[] argv) throws Exception {

        int n = 2;

        boolean zeroBased = true;

        System.out.println(listAllCombinations(n, zeroBased));

    }


    public static List<Set<Integer>> listAllCombinations(int n,

            boolean zeroBased) {

        List<Set<Integer>> allCombinations;
// 来自 时代Java - N o w  J a v a . c o m

        allCombinations = new ArrayList<Set<Integer>>();

        for (int k = 0; k < n; k++) {

            allCombinations.addAll(listCombinationsFixed2(n, k, zeroBased));

        }


        return allCombinations;

    }


    public static List<Set<Integer>> listCombinationsFixed2(final int n,

            final int k, final boolean isZeroBased) {

        List<Set<Integer>> combinations = new ArrayList<Set<Integer>>();


        //System.out.println("will get combinations with (n,k)=(" + n + "," + k + ")");


        Integer[] combination = null;


        if (k == 0 || k == n) {

            combination = new Integer[n];

            for (int i = 0; i < n; i++) {

                combination[i] = i;

            }

        } else {

            combination = new Integer[k];

            for (int i = 0; i < k; i++) {

                combination[i] = i;

            }

        }


        if (isZeroBased) {

            combinations.add(new HashSet<Integer>(Arrays

                    .asList(combination)));

        } else {

            Integer[] tempCombination = new Integer[combination.length];


            for (int i = 0; i < combination.length; i++) {

                tempCombination[i] = combination[i] + 1;

            }

            combinations.add(new HashSet<Integer>(Arrays

                    .asList(tempCombination)));

        }


        while (nextCombination(combination, n, k)) {


            if (isZeroBased) {

                combinations.add(new HashSet<Integer>(Arrays

                        .asList(combination)));

            } else {

                Integer[] tempCombination = new Integer[combination.length];


                for (int i = 0; i < combination.length; i++) {

                    tempCombination[i] = combination[i] + 1;

                }

                combinations.add(new HashSet<Integer>(Arrays

                        .asList(tempCombination)));

            }


        }


        return combinations;

    }


    private static boolean nextCombination(Integer comb[], int n, int k) {

        int i = k - 1;

        if (i == -1) {

            return false;

            
展开阅读全文