我已经花了很多时间来解决我的问题。 我解决了很多问题,但这个问题仍在困扰我:S。我已经很长时间没有接触Java编程(总的编程)了,所以请大家谅解! ;)
我的目标是从整数数组中获取所有可能的组合。 当我使用以下代码应用于测试整数数组{1,2,3,4}时,我希望得到:
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
2 1 3 4
2 1 4 3
(...)
但是这就是我得到的结果:
1 2 3 4
1 2 3 4 4 3
1 2 3 4 4 3 3 2 4
有人有线索,建议或甚至解决方案吗?先感谢您!
public class Calculation{
(...)
public void Permute(ArrayList<Integer> soFar,ArrayList<Integer> rest){
if(rest.isEmpty()) this.fillMatrice(convertIntegers(soFar)); // there it goes in a previously created arrow of int
else{
for(int k=0;k<rest.size();k++){
ArrayList<Integer> next=new ArrayList<Integer>();
next=soFar;
next.add(rest.get(k));
ArrayList<Integer> remaining=new ArrayList<Integer>();
List<Integer> sublist = rest.subList(0, k);
for(int a=0;a<sublist.size();a++) remaining.add(sublist.get(a));
sublist = rest.subList(k+1,rest.size());
for(int a=0;a<sublist.size();a++) remaining.add(sublist.get(a));
Permute(next,remaining);
}
}
}
public static ArrayList<Integer> convertArray(int[] integers){
ArrayList<Integer> convArray=new ArrayList<Integer>();
for(int i=0;i<integers.length;i++) convArray.add(integers[i]);
return convArray;
}
public static int[] convertIntegers(List<Integer> integers){
int[] ret = new int[integers.size()];
for(int i=0;i<ret.length;i++) ret[i]=integers.get(i).intValue();
return ret;
}
public Calculation() {
(...)
ArrayList<Integer> soFar=new ArrayList<Integer>();
int[] test={1,2,3,4};
Permute(soFar,convertArray(test));
}