Java 如何生成给定列表的幂集?
我试图生成一个集合,其中包含给定长度N列表中所有2^N-1个可能的组合。该集合将组合中的元素数映射到包含特定长度组合的有序组合列表。例如,对于列表:Java 如何生成给定列表的幂集?,java,algorithm,list,combinations,Java,Algorithm,List,Combinations,我试图生成一个集合,其中包含给定长度N列表中所有2^N-1个可能的组合。该集合将组合中的元素数映射到包含特定长度组合的有序组合列表。例如,对于列表: [A, B, C, D] 我想生成地图: { 1 -> [{A}, {B}, {C}, {D}] 2 -> [{A, B}, {A, C}, {A, D}, {B, C}, {B, D}, {C, D}] 3 -> [{A, B, C}, {A, B, D}, {A, C, D}, {B, C, D}]
[A, B, C, D]
我想生成地图:
{
1 -> [{A}, {B}, {C}, {D}]
2 -> [{A, B}, {A, C}, {A, D}, {B, C}, {B, D}, {C, D}]
3 -> [{A, B, C}, {A, B, D}, {A, C, D}, {B, C, D}]
4 -> [{A, B, C, D}]
}
生成的数据库应保持原始顺序(其中[]
表示有序的系列(列表
),而{}
表示未排序的组(集合
),并尽可能快地运行
我整天都在与一些递归代码作斗争(我知道实现应该是递归的),但无法找到它的底部
是否有一个我可以使用的参考/a这种算法的现成实现?您所寻找的基本上是(减去可能的空集)。番石榴实际上有一种方法可以做到这一点:。如果您想自己编写该方法,可以查看以查看该方法是如何实现的;您可能需要修改它以返回
列表
,而不是集合
,因为您希望保留顺序,尽管此更改不应太剧烈。一旦你有了幂集,迭代它并构造你想要的映射应该很简单。你所要求的是生成一个集的所有可能子集。您可以将其视为迭代所有可能的大小为N(列表大小)的二进制数组:
为什么呢?答案很简单:1表示元素存在于子集中,而0表示元素不存在
因此,基本算法是显而易见的:
s = [A, B, C, D]
for i=0 to 2^N-1:
b = convert_number_to_bin_array(i)
ss = calculate_subset_based_on_bin_array(s, b)
print ss
其中,基于\u bin\u数组计算\u子集
迭代b
和s
,并从s[当前]
中选择元素,其中b[当前]=1
以上内容将打印出所有现有子集。您可以调整此算法,以获得您在问题中要求的映射。我测试了Elist提出的代码,发现了错误 下面是一个建议的更正:(在函数getPermutation()的最后一个else中,我做了两个更改)
公共类OrderedPowerSet{
私有ArrayList输入列表;
公共int N;
专用地图=
新的HashMap();
公共OrderedPowerSet(ArrayList列表){
输入列表=列表;
N=list.size();
}
公共列表GetPermutionsList(int-elementCount){
if(elementCount<1 | | elementCount>N){
抛出新的IndexOutOfBoundsException(
“只能为介于1到“+N”之间的计数生成置换”;
}
if(映射容器(元素计数)){
返回map.get(elementCount);
}
ArrayList=新建ArrayList();
if(elementCount==N){
添加(新HashSet(inputList));
}else if(elementCount==1){
对于(int i=0;i
}以下是我测试过的代码,用于生成给定数组中所有可能的组合:
enter code here
import java.util.Arrays;
public class PasswordGen {
static String[] options = { "a", "b", "c", "d" };
static String[] places = new String[options.length];
static int count;
public static void main(String[] args) {
// Starting with initial position of a i.e. 0
sequence(0, places.clone());
}
private static void sequence(int level, String[] holder) {
if (level >= options.length) {
// combination complete
System.out.println("" + (++count) + " Combination "
+ Arrays.toString(holder));
return;
}
String val = options[level];
String[] inrHolder = null;
for (int c = 0; c < holder.length; c++) {
inrHolder = holder.clone();
if (inrHolder[c] == null) {
inrHolder[c] = val;
sequence(level + 1, inrHolder.clone());
}
}
return;
}
}
在此处输入代码
导入java.util.array;
公共类密码发生器{
静态字符串[]选项={“a”、“b”、“c”、“d”};
静态字符串[]位置=新字符串[options.length];
静态整数计数;
公共静态void main(字符串[]args){
//从a的初始位置开始,即0
序列(0,places.clone());
}
私有静态无效序列(int级别,字符串[]持有者){
如果(级别>=options.length){
//组合完成
System.out.println(“+(++计数)+”组合”
+数组。toString(holder));
回来
}
字符串val=选项[级别];
字符串[]inrHolder=null;
对于(int c=0;c
公共静态列表GetCombinationsList(列表元素)
{
//返回带有空字符串的列表
if(elements.size()==0){
List allLists=new ArrayList();
所有列表。添加(“”);
返回所有列表;
}
字符串first_ele=元素。删除(0);
List rest=getCombinationsList(元素);
int restsize=rest.size();
//将第一个元素映射到其余每个元素。
for(int i=0;i
这个幂集是SICP“计算机编程的结构和解释”一书中的练习之一。每个程序员都应该阅读它。解决这个问题有多种方法,但最简单的方法是使用递归。下面我提供了迭代和递归方法来解决生成集合的所有组合的问题。这两种方法的总体思路都是生成属于要选择的元素的索引集 对于递归方法,您希望跟踪三条信息:一个布尔数组,指示是否选择了项,您在项列表中的位置,以及一个变量r,跟踪剩余要选择的元素数。那么只要
public class OrderedPowerSet<E> {
private ArrayList<E> inputList;
public int N;
private Map<Integer, List<Set<E>>> map =
new HashMap<Integer, List<Set<E>>>();
public OrderedPowerSet(ArrayList<E> list) {
inputList = list;
N = list.size();
}
public List<Set<E>> getPermutationsList(int elementCount) {
if (elementCount < 1 || elementCount > N) {
throw new IndexOutOfBoundsException(
"Can only generate permutations for a count between 1 to " + N);
}
if (map.containsKey(elementCount)) {
return map.get(elementCount);
}
ArrayList<Set<E>> list = new ArrayList<Set<E>>();
if (elementCount == N) {
list.add(new HashSet<E>(inputList));
} else if (elementCount == 1) {
for (int i = 0 ; i < N ; i++) {
Set<E> set = new HashSet<E>();
set.add(inputList.get(i));
list.add(set);
}
} else {
for (int i = 0 ; i < N-elementCount ; i++) {
@SuppressWarnings("unchecked")
ArrayList<E> subList = (ArrayList<E>)inputList.clone(); // one change
subList.remove(0);
OrderedPowerSet<E> subPowerSet =
new OrderedPowerSet<E>(subList);
for (Set<E> s : subPowerSet.getPermutationsList(elementCount-1)) {
Set<E> set = new HashSet<E>();
set.add(inputList.get(i));
set.addAll(s);
list.add(set); // second change
}
}
}
map.put(elementCount, list);
return map.get(elementCount);
}
enter code here
import java.util.Arrays;
public class PasswordGen {
static String[] options = { "a", "b", "c", "d" };
static String[] places = new String[options.length];
static int count;
public static void main(String[] args) {
// Starting with initial position of a i.e. 0
sequence(0, places.clone());
}
private static void sequence(int level, String[] holder) {
if (level >= options.length) {
// combination complete
System.out.println("" + (++count) + " Combination "
+ Arrays.toString(holder));
return;
}
String val = options[level];
String[] inrHolder = null;
for (int c = 0; c < holder.length; c++) {
inrHolder = holder.clone();
if (inrHolder[c] == null) {
inrHolder[c] = val;
sequence(level + 1, inrHolder.clone());
}
}
return;
}
}
static Map<Integer, List<LinkedList<Integer>>> powerset = new HashMap<>();
public static void main(String[] args) throws IOException {
powerset(Arrays.asList(1, 2, 3));
for (Integer key : powerset.keySet()) {
System.out.print(key + " -> ");
System.out.println(Arrays.toString(powerset.get(key).toArray()));
}
}
static void powerset(List<Integer> src) {
powerset(new LinkedList<>(), src);
}
private static void powerset(LinkedList<Integer> prefix, List<Integer> src) {
if (src.size() > 0) {
prefix = new LinkedList<>(prefix); //create a copy to not modify the orig
src = new LinkedList<>(src); //copy
Integer curr = src.remove(0);
collectResult(prefix, curr);
powerset(prefix, src);
prefix.add(curr);
powerset(prefix, src);
}
}
private static void collectResult(LinkedList<Integer> prefix, Integer curr) {
prefix = new LinkedList<>(prefix); //copy
prefix.add(curr);
List<LinkedList<Integer>> addTo;
if (powerset.get(prefix.size()) == null) {
List<LinkedList<Integer>> newList = new LinkedList<>();
addTo = newList;
} else {
addTo = powerset.get(prefix.size());
}
addTo.add(prefix);
powerset.put(prefix.size(), addTo);
}
1 -> [[1], [2], [3]]
2 -> [[2, 3], [1, 2], [1, 3]]
3 -> [[1, 2, 3]]
public static List<String> getCombinationsLists(List<String> elements)
{
//return list with empty String
if(elements.size() == 0){
List<String> allLists = new ArrayList<String>();
allLists.add("");
return allLists ;
}
String first_ele = elements.remove(0);
List<String> rest = getCombinationsLists(elements);
int restsize = rest.size();
//Mapping the first_ele with each of the rest of the elements.
for (int i = 0; i < restsize; i++) {
String ele = first_ele + rest.get(i);
rest.add(ele);
}
return rest;
}
/**
* Here we present two methods (recursive and iterative) of generating all
* the combinations of a set by choosing only r of n elements.
*
* Time Complexity: O( n choose r )
*
* @author William Fiset, Micah Stairs
**/
public class Combinations {
// This method finds all the combinations of size r in a set
public static void combinationsChooseR(int[] set, int r) {
if (r < 0) return;
if (set == null) return;
boolean [] used = new boolean[set.length];
combinations(set, r, 0, used);
}
// To find all the combinations of size r we need to recurse until we have
// selected r elements (aka r = 0), otherwise if r != 0 then we need to select
// an element which is found after the position of our last selected element
private static void combinations(int[] set, int r, int at, boolean[] used) {
final int N = set.length;
// If there are more elements left to select than what are available
// This is a short circuiting optimization we can take advantage of
int elementsLeftToPick = N - at;
if (elementsLeftToPick < r) return;
// We selected 'r' elements so we found a valid subset!
if (r == 0) {
System.out.print("{ ");
for (int i = 0; i < N; i++)
if (used[i])
System.out.print(set[i] + " ");
System.out.println("}");
} else {
for (int i = at; i < N; i++) {
// Try including this element
used[i] = true;
combinations(set, r - 1, i + 1, used);
// Backtrack and try the instance where we did not include this element
used[i] = false;
}
}
}
// Use this method in combination with a do while loop to generate all the
// combinations of a set choose r in a iterative fashion. This method returns
// false once the last combination has been generated.
// NOTE: Originally the selection needs to be initialized to {0,1,2,3 ... r-1}
public static boolean nextCombination(int[] selection, int N, int r) {
if (r > N) throw new IllegalArgumentException("r must be <= N");
int i = r - 1;
while (selection[i] == N - r + i)
if (--i < 0) return false;
selection[i]++;
for (int j = i + 1; j < r; j++) selection[j] = selection[i] + j - i;
return true;
}
public static void main(String[] args) {
// Recursive approach
int R = 3;
int[] set = {1,2,3,4,5};
combinationsChooseR(set, R);
// prints:
// { 1 2 3 }
// { 1 2 4 }
// { 1 2 5 }
// { 1 3 4 }
// { 1 3 5 }
// { 1 4 5 }
// { 2 3 4 }
// { 2 3 5 }
// { 2 4 5 }
// { 3 4 5 }
// Suppose we want to select all combinations of colors where R = 3
String[] colors = {"red", "purple", "green", "yellow", "blue", "pink"};
R = 3;
// Initialize the selection to be {0, 1, ... , R-1}
int[] selection = { 0, 1, 2 };
do {
// Print each combination
for (int index : selection)
System.out.print(colors[index] + " ");
System.out.println();
} while( nextCombination(selection, colors.length, R) );
// prints:
// red purple green
// red purple yellow
// red purple blue
// red purple pink
// red green yellow
// red green blue
// red green pink
// red yellow blue
// red yellow pink
// red blue pink
// purple green yellow
// purple green blue
// purple green pink
// purple yellow blue
// purple yellow pink
// purple blue pink
// green yellow blue
// green yellow pink
// green blue pink
// yellow blue pink
}
}
public class OrderedPowerSet<E> {
private static final int ELEMENT_LIMIT = 12;
private List<E> inputList;
public int N;
private Map<Integer, List<LinkedHashSet<E>>> map =
new HashMap<Integer, List<LinkedHashSet<E>>>();
public OrderedPowerSet(List<E> list) {
inputList = list;
N = list.size();
if (N > ELEMENT_LIMIT) {
throw new RuntimeException(
"List with more then " + ELEMENT_LIMIT + " elements is too long...");
}
}
public List<LinkedHashSet<E>> getPermutationsList(int elementCount) {
if (elementCount < 1 || elementCount > N) {
throw new IndexOutOfBoundsException(
"Can only generate permutations for a count between 1 to " + N);
}
if (map.containsKey(elementCount)) {
return map.get(elementCount);
}
ArrayList<LinkedHashSet<E>> list = new ArrayList<LinkedHashSet<E>>();
if (elementCount == N) {
list.add(new LinkedHashSet<E>(inputList));
} else if (elementCount == 1) {
for (int i = 0 ; i < N ; i++) {
LinkedHashSet<E> set = new LinkedHashSet<E>();
set.add(inputList.get(i));
list.add(set);
}
} else {
list = new ArrayList<LinkedHashSet<E>>();
for (int i = 0 ; i <= N - elementCount ; i++) {
@SuppressWarnings("unchecked")
ArrayList<E> subList = (ArrayList<E>)((ArrayList<E>)inputList).clone();
for (int j = i ; j >= 0 ; j--) {
subList.remove(j);
}
OrderedPowerSet<E> subPowerSet =
new OrderedPowerSet<E>(subList);
List<LinkedHashSet<E>> pList =
subPowerSet.getPermutationsList(elementCount-1);
for (LinkedHashSet<E> s : pList) {
LinkedHashSet<E> set = new LinkedHashSet<E>();
set.add(inputList.get(i));
set.addAll(s);
list.add(set);
}
}
}
map.put(elementCount, list);
return map.get(elementCount);
}
}