首页 > 其他 > 详细

[Leetcode 46]全排列 Permutations 递归

时间:2018-11-18 10:08:39      阅读:129      评论:0      收藏:0      [点我收藏+]

【题目】

Given a collection of distinct integers, return all possible permutations.

数组的组合情况。

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

【思路】

求子集,排列组合的数组题有固定模板。

【代码】

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> ans=new ArrayList<>();
        List<Integer> tmp=new ArrayList<>();
        fun(ans,tmp,nums);
        return ans;
    }
    public void fun(List<List<Integer>> ans,List<Integer> tmp,int[] nums){
        if(tmp.size()==nums.length){
            ans.add(new ArrayList<>(tmp));
        }
        else{
            for(int i=0;i<nums.length;i++){
                if(tmp.contains(nums[i]))
                    continue;
                tmp.add(nums[i]);
                fun(ans,tmp,nums);
                tmp.remove(tmp.size()-1);
            }
        }
    }
}

 

[Leetcode 46]全排列 Permutations 递归

原文:https://www.cnblogs.com/inku/p/9976173.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!