LeetCode-46. Permutations

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

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> re = new ArrayList<List<Integer>>();
        List<Integer> cur = new ArrayList<>();
        boolean[] isVisit = new boolean[nums.length];
        help(nums,re,cur,isVisit);
        return re;
    }
    private void help(int[] nums,List<List<Integer>> re,List<Integer> cur,boolean[] isVisit){
        if(cur.size() == nums.length){
            List<Integer> l =new ArrayList<Integer>(cur);
            re.add(l);
            return;
        }
        for(int i = 0;i<nums.length;i++){
            if(!isVisit[i]){
                isVisit[i]= true;
                cur.add(nums[i]);
                help(nums,re,cur,isVisit);
                cur.remove(cur.size()-1);
                isVisit[i] = false;
            }
            
        }
    }

 

posted @ 2019-07-18 10:24  月半榨菜  阅读(81)  评论(0编辑  收藏  举报