46. 全排列

46. 全排列

给定一个 没有重复 数字的序列,返回其所有可能的全排列。

示例:

输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

class Solution {
    public List> permute(int[] nums) {
        List> lists = new ArrayList<>();
        if(nums == null || nums.length == 0) return lists;
        boolean[] visited = new boolean[nums.length];
        bt(nums,new ArrayList<>(),lists,visited);
        return lists;
    }
    private void bt(int[] nums,List list,List> lists,boolean[] visited){
        if(list.size() == nums.length){
            lists.add(new ArrayList<>(list));
            return;
        }
        for(int j = 0;j < nums.length;j++){
            if(!visited[j]){
                visited[j] = true;
                list.add(nums[j]);
                bt(nums,list,lists,visited);
                visited[j] = false;
                list.remove(list.size() - 1);
            }
        }
    }
}

47. 全排列 II

给定一个可包含重复数字的序列,返回所有不重复的全排列。

示例:

输入: [1,1,2]
输出:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

class Solution {
    public List> permuteUnique(int[] nums) {       
        List> lists = new ArrayList<>();
        if(nums == null || nums.length == 0) return lists;
        boolean[] visited = new boolean[nums.length];
        //需要排序先
        Arrays.sort(nums);
        bt(nums,new ArrayList<>(),lists,visited);
        return lists;
    }
    private void bt(int[] nums,List list,List> lists,boolean[] visited){
        if(list.size() == nums.length){
            lists.add(new ArrayList<>(list));
            return;
        }
        for(int j = 0;j < nums.length;j++){
            if(visited[j] || (j > 0 && nums[j] == nums[j - 1] && !visited[j - 1])){
                continue;
            }
            visited[j] = true;
            list.add(nums[j]);
            bt(nums,list,lists,visited);
            visited[j] = false;
            list.remove(list.size() - 1);
            
        }
    }
}

 

你可能感兴趣的:(46. 全排列)