IncredibleThings

导航

LeetCode-Permutations

Given a collection of distinct 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],
  [3,2,1]
]
public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        if(nums==null || nums.length==0){return null;}
        List<List<Integer>> resList=new ArrayList<List<Integer>>();
        List<Integer> item=new ArrayList<Integer>();
        boolean[] isVisited=new boolean[nums.length];
        backTracking(nums, item, resList, isVisited);
        return resList;
    }
    public void backTracking(int[] nums, List<Integer> item, List<List<Integer>> resList, boolean[] isVisited){
        if(item.size()==nums.length){
            resList.add(new ArrayList<Integer>(item));
            return;
        }
        for(int i=0; i<nums.length; i++){
            if(!isVisited[i]){
                isVisited[i]=true;
                item.add(nums[i]);
                backTracking(nums, item, resList, isVisited);
                item.remove(item.size()-1);
                isVisited[i]=false;
            }
        }
    }
}

 

posted on 2016-08-24 01:07  IncredibleThings  阅读(132)  评论(0编辑  收藏  举报