全排列2 · Permutations

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]
数组记得要排序
一些问题不能理解,那就这样吧。本来中等的题目就不好理解,得考虑一下投入产出比了。

public class Solution {
    /*
     * @param nums: A list of integers.
     * @return: A list of permutations.
     */
    public List<List<Integer>> permuteUnique(int[] nums) {
        //corner case
        List<List<Integer>> results = new ArrayList<>();
        List<Integer> permutations = new ArrayList<>();
        int[] visited = new int[nums.length];
        
        if (nums == null) {
            return null;
        }
        
        if (nums.length == 0) {
            //return new ArrayList<>();
            results.add(new ArrayList<>());
            return results;
        }
        
        
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            visited[i] = 0;
        }
        
        //helper
        helper(nums, permutations, visited, results);
        //return
        return results;
    }
    //helper
    public void helper (int[] nums, List<Integer> permutations, 
    int[] visited, List<List<Integer>> results) {
        if (permutations.size() == nums.length) {
            results.add(new ArrayList<>(permutations));
            return ;//
        }
        
        for (int i = 0; i < nums.length; i++) {
            if (visited[i] == 1) 
                continue;
            
            if ((i != 0) && (nums[i] == nums[i - 1]) && (visited[i - 1] == 0)) 
                continue;
            
            permutations.add(nums[i]);
            visited[i] = 1;
            helper(nums, permutations, visited, results);
            visited[i] = 0;
            permutations.remove(permutations.size() - 1);
        }
    }
}
View Code

 

 
posted @ 2020-06-25 22:35  苗妙苗  阅读(115)  评论(0编辑  收藏  举报