数组的全排列这个题很早就了解过,但一直没有做,今天在leetcode上遇到了这个题,原题如下:
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]
.
题目地址为:https://leetcode.com/problems/permutations/
这里使用一个类似深度遍历方法,假设已经排好了前i-1个元素,在排第i个元素时,这个元素可能的摆放位置有i个,即摆放在前i-1个元素的第0个位置,第1个位置,...,第i-1个位置,每摆放一个位置就向下递归一次,递归返回之后,从刚才那个位置取出来,摆放在下一个位置。代码如下:
public void helper(int[] nums,int cur,ArrayList<Integer> list,List<List<Integer>> res){
if(list.size()==nums.length){
res.add(new ArrayList<Integer>(list));
return;
}
for(int i=cur;i<nums.length;i++){
for(int j=0;j<=list.size();j++){
list.add(j, nums[i]);//依次摆放在第j个位置,注意list.size()这个位置也是可以摆放的
helper(nums,i+1,list, res);
list.remove(j);
}
}
}
//求nums这些数的全排列
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
helper(nums, 0, new ArrayList<Integer>(), res);
return res;
}
这个想法很直观也很简单,但是竟然击败了99%以上的java代码,截图如下,大家都是怎么做的,还是系统出现问题了。