【题目】

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);
            }
        }
    }
}

 

 posted on 2018-11-17 23:06  alau  阅读(116)  评论(0编辑  收藏  举报