数组的全排列

数组的全排列这个题很早就了解过,但一直没有做,今天在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代码,截图如下,大家都是怎么做的,还是系统出现问题了。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值