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。
用的是递归的思想来做的。
1. 对num[]进行排序。题目没有说明给的数组是否是有序的,也没有有求返回的list是否要按照有序顺序返回,但是为了统一,还是先排序吧。
2. 在递归之前先把int[]转为list<integer>。不能用库函数中的Arrays.asList(num)来直接把int[]->list<Integer>。因为Arrays.asList接受的是对象,所以必须是Integer[]之类的。而转成integer[]也只有for循环,那还不如直接list.add来进行。
3. 递归。
递归的退出条件是:list<>只有一个元素。
当list有多个元素的时候,每次拷贝list为tmplist,for循环遍历tmplist,从tmplist中提取出一个元素,加入到把递归结果集中的list的头部即:list.add(0,tmplist.remove(x));
4.返回list<list<Integer>>。
上代码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Permutations {
/**
* 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].
* @param args
*/
public List<List<Integer>> getpermute(List<Integer> num) {//递归函数
List<List<Integer>> resultLists=new ArrayList<>();
if(num.size()==1){//退出条件
resultLists.add(num);
}
else{//递归
for(int indexnum=0;indexnum<num.size();++indexnum){
List<Integer> numtmp=new ArrayList<>(num);//拷贝,
int first=numtmp.remove(indexnum);
List<List<Integer>> tmplLists=getpermute(numtmp);
for (List<Integer> list : tmplLists) {
list.add(0, first);//添加移出的元素到头部
resultLists.add(list);
}
}
}
return resultLists;
}
public List<List<Integer>> permute(int[] num) {//把num[]转为 List<Integer>
Arrays.sort(num);
List<Integer> numlist=new ArrayList<>();
for(int indexnum=0;indexnum<num.length;++indexnum)numlist.add(num[indexnum]);
return getpermute(numlist);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}