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]
.
实现的思路是使用递归,发现用
List<List<Integer>> res = new ArrayList<List<Integer>>();
这个方法初始化二元list数组是有问题的,打印结果虽然正确但是add到结果集的时候会出问题。我想应该是java语法部分的东西了。日后解决下,先往下做。
代码:
package codes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Permutations {
public static void main(String[] args) {
int [] nums = {1,2,3};
List<List<Integer>> res = new Permutations().permute(nums);
for( List<Integer> list : res){
for(int item : list){
System.out.print(item+" ");
}
System.out.println();
}
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> list = convertToList(nums);
// 递归
perm(list,0,nums.length,res);
return res;
}
private void perm(List<Integer> array, int begin,int end,List<List<Integer>> res) {
if( begin == end ){
res.add(array);
for(int i : array){
System.out.print(" "+i);
}
System.out.println();
}else{
for( int i = begin; i<array.size();i++){
swap(i,begin,array);
perm(array,begin+1,end,res);
swap(i,begin,array);
}
}
}
public void swap(int a,int b,List<Integer> list){
//System.out.println("old a,b"+list.get(a)+" "+ list.get(b));
int tmp = list.get(a);
list.set(a, list.get(b)) ;
list.set(b, tmp);
//System.out.println("new a,b"+list.get(a)+" "+ list.get(b));
}
public List<Integer> convertToList(int[] num){
List<Integer> list = new ArrayList<Integer>();
for(int i=0;i<num.length;i++){
list.add(num[i]);
}
//System.out.print("array Size:"+list.size());
return list;
}
}