码迷,mamicode.com
首页 > 其他好文 > 详细

全排列2 · Permutations

时间:2020-06-25 23:47:18      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:show   不能   res   ==   int   arrays   ide   unique   col   

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

 

 

全排列2 &#183; Permutations

标签:show   不能   res   ==   int   arrays   ide   unique   col   

原文地址:https://www.cnblogs.com/immiao0319/p/13193250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!