我输入了一组元素,我们假设它们是字符串:
String[] elements = {"A","B","C","D"};
我想生成大小为1,2和3(直到n-1)个元素的所有排列,而不重复任何元素。
所以输出看起来完全像这样:
A
B
C
D
AB
AC
AD
BC
BD
CD
ABC
ABD
ACD
BCD
当前代码我已生成所有排列,但有重复:(
public static String[] getAllLists(String[] elements, int lengthOfList)
{
//initialize our returned list with the number of elements calculated above
String[] allLists = new String[(int)Math.pow(elements.length, lengthOfList)];
//lists of length 1 are just the original elements
if(lengthOfList == 1)
return elements;
else
{
//the recursion--get all lists of length 3, length 2, all the way up to 1
String[] allSublists = getAllLists(elements, lengthOfList - 1);
//append the sublists to each element
int arrayIndex = 0;
for(int i = 0; i < elements.length; i++)
{
for(int j = 0; j < allSublists.length; j++)
{
//add the newly appended combination to the list
allLists[arrayIndex] = elements[i] + allSublists[j];
arrayIndex++;
}
}
return allLists;
}
}
public static void main()
{
String[] elements = {"A","B","C","D"};
for(int i=1; i<=elements.length; i++)
{
String[] result = getAllLists(elements, i);
for(int j=0; j<result.length; j++)
{
System.out.println(result[j]);
}
}
}
答案 0 :(得分:3)
快速和肮脏的关键是按字典顺序构建新的字符串... 令牌包含A,B,C,D 结果还包含启动时的A,B,C,D
用于运行后显示的输出
result = perm(令牌,结果,1,3);
public static List<String> perm(List<String> tokens, List<String> result, int currentLength, int maxLength){
if(currentLength == maxLength){
return result;
}
List<String> gen = new ArrayList<String>();
for(String s : result){
for(String s1 : tokens){
if(s.equals(s1) || s.contains(s1)){
continue;
}else{
String temp = s+s1;
char[] ca = temp.toCharArray();
Arrays.sort(ca);
String res = "";
for(char c : ca){
res+=c;
}
if(gen.contains(res)){
continue;
}
gen.add(res);
}
}
}
if(gen.size() > 0){
result.addAll(perm(tokens,gen,currentLength+1,maxLength));
}
return result;
}
答案 1 :(得分:0)
我改变了你的代码位。试试这个。
public static String[] getAllLists(String[] elements, int lengthOfList) {
Set<String> result = new HashSet<String>();
//lists of length 1 are just the original elements
if(lengthOfList == 1)
return elements;
else
{
//the recursion--get all lists of length 3, length 2, all the way up to 1
String[] allSublists = getAllLists(elements, lengthOfList - 1);
for(int i = 0; i < elements.length; i++) {
for (int j = i +1; j < allSublists.length; j++) {
//Check duplicate characters
if(allSublists[j].indexOf(elements[i].charAt(0)) == -1) {
String s = elements[i] + allSublists[j];
char[] c = s.toCharArray();
Arrays.sort(c);
result.add(new String(c)); // Add sorted String
}
}
}
return result.toArray(new String[result.size()]);
}
}