首页 > 其他 > 详细

全排列2 · Permutations

时间:2020-06-25 23:41:20      阅读:86      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!