Given a collection of numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
Solution:一开始想递归来算Ann = An-1 n-1 * n(也就是在An-1 n-1基础之上在每个序列的元素缝隙之间插入数字N)
干脆循环来算,从A11到A22再到Ann也差不多
1 public List<List<Integer>> permute(int[] num) { 2 List<List<Integer>> list = new ArrayList<List<Integer>>(); 3 List<Integer> l = new ArrayList<Integer>(); 4 l.add(num[0]); 5 list.add(l); 6 for(int i=1;i<num.length;i++){ 7 int listNum = list.size(); 8 for(int j=0;j<listNum;j++){ 9 int k = 0; 10 int listNodeNum = list.get(j).size(); 11 while(k< listNodeNum){ 12 List<Integer> subList = new ArrayList<Integer>(list.get(j)); 13 subList.add(k,num[i]); 14 list.add(subList); 15 k++; 16 } 17 list.get(j).add(k,num[i]); 18 } 19 } 20 return list; 21 }