我想要獲得與輸入arrayList長度相同的ArrayList的所有可能的排列組合。即1,2,3的ArrayList將導致123,132,213,231,321,312,不包括諸如1,2,12,13等的較短排列。這是我迄今爲止的代碼:獲取一個ArrayList的所有可能的排列的ArrayList
public void getAllPermutations(ArrayList<coordinate> coords) {
ArrayList<coordinate> sub = new ArrayList<coordinate>();
permutateSub(sub, coords);
}
private ArrayList<ArrayList<coordinate>> permutateSub(ArrayList<coordinate> sub,
ArrayList<coordinate> coords) {
int n = coords.size();
if(n == 0) System.out.println(sub);
else {
if(sub.size()==n) {
System.out.println(sub);
for(int i = 0; i<n; i++) {
ArrayList<coordinate> a = new ArrayList<coordinate>(sub);
a.add(coords.get(i));
ArrayList<coordinate> b = new ArrayList<coordinate>(coords);
b.remove(i);
permutateSub(a, b);
}
}
}
座標是一個類,只有x,y,並被訪問以保存項目的2D點。
當前我正在使用此代碼將其打印到控制檯,但我也希望如果有人能夠闡明我如何將它存儲到ArrayList>中。謝謝。
看起來這可能是http://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string – mkobit 2014-09-06 21:10:03
有趣的副本,我看到方法'permutateSub'的聲明就好像它應該返回一個'ArrayList>'對象,但是我在函數的代碼中沒有看到'return'。 –
2014-09-06 21:20:05
糟糕,我的錯誤。無論如何,它仍然會返回更短的排列。 – AHalbert 2014-09-06 21:26:34