Java tutorial
//package com.java2s; /*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 The ConQAT Project | | | | Licensed under the Apache License, Version 2.0 (the "License"); | | you may not use this file except in compliance with the License. | | You may obtain a copy of the License at | | | | http://www.apache.org/licenses/LICENSE-2.0 | | | | Unless required by applicable law or agreed to in writing, software | | distributed under the License is distributed on an "AS IS" BASIS, | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | | See the License for the specific language governing permissions and | | limitations under the License. | +-------------------------------------------------------------------------*/ import java.util.ArrayList; import java.util.List; public class Main { /** * Returns the power set of the given input list. Note that elements are * treated as unique, i.e. we do not really use set semantics here. Also * note that the returned list has 2^n elements for n input elements, so the * input list should not be too large. */ public static <T> List<List<T>> getPowerSet(List<T> input) { return getPowerSet(input, 0); } /** * Returns the power set of the given input list, only considering elements * at or after index <code>start</code>. */ private static <T> List<List<T>> getPowerSet(List<T> input, int start) { ArrayList<List<T>> result = new ArrayList<>(); if (start >= input.size()) { result.add(new ArrayList<T>()); } else { T element = input.get(start); for (List<T> list : getPowerSet(input, start + 1)) { List<T> copy = new ArrayList<>(); copy.add(element); copy.addAll(list); result.add(list); result.add(copy); } } return result; } }