我有一个set =(1,2,3),我需要获得具有不同序列的所有可能的子集(具有重复元素)。输出外观:
1
2
3
1,2
1,3
2,1
2,3
3,1
3,2
1,2,3
1,3,2
2,1,3
2,3,1
3,1,2
3,2,1
有人可以帮助我吗? thxx
答案 0 :(得分:3)
如果您需要子集,那么Google Guava会为您提供一种方法:
但是在你的例子中你有一些重复的集合(记住,集合是无序的)。因此,您可能希望获得每个子集的所有可能的排列:
答案 1 :(得分:0)
通过使用按位运算查找所有组合可以解决问题。
这个想法是:生成给定数组(集合)的所有子集,这个集合称为幂集。对于每个子集(组合),也找到它的排列。
请参阅以下教程,了解如何使用Bit Wise操作找到所有组合。 http://www.codechef.com/wiki/tutorial-bitwise-operations
void PERMUTE()
{
/*PERMUTATION FUNCTION THAT PERMUTES THE SUBSET ARRAY*/
}
public static void main(String[] args)
{
// TODO code application logic here
int Set[]={1,2,3};
int n=Set.length;
for (int i = 0; i <= (1 << n); ++i)
{
System.out.print("[");
int subsetSz=0;
int A[]=new int[100];
for (int j = 0; j < n; ++j)
{
if ((i & 1 << j)!=0)
{
System.out.print(Set[j]+",");
A[subsetSz++]=Set[j];
}
}
System.out.println("]");
/*Permute the subset*/
if(subsetSz>1)
{
PERMUTE(A);
}
}
}