[Leetcode学习-java]permutations-ii

问题:

难度:medium

说明:

全排列,但是存在重复元素,并且每个元素只使用一次,要求返回所有不重复的排列。

题目连接:https://leetcode.com/problems/permutations-ii/

相关算法:

[Codewar训练]Permutations(String)(全排列):https://blog.csdn.net/qq_28033719/article/details/105860028

输入范围:

  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10

输入案例:

Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
 [1,2,1],
 [2,1,1]]

Example 2:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

我的代码:

全排列很明显用 递归 + 循环,如果元素不重复使用,就用 used 表示已经使用,还有创建暂存表,具体的话都会传一堆参考参数,写起来差不多。

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
            return recurtion(nums, new boolean[nums.length], 0, nums.length, new ArrayList<List<Integer>>(), new int[nums.length]);
        }

        public List<List<Integer>> recurtion(int[] nums, boolean[] used, int index, int len, List<List<Integer>> res, int[] temp) {
            if(index == len) {
                List<Integer> list = new ArrayList<Integer>();
                for(int i : temp) list.add(i);
                res.add(list);
                return res;
            }
            HashSet<Integer> set = new HashSet<Integer>();
            for(int i = 0;i < len;i ++) {
                if(!used[i] && !set.contains(nums[i])) {
                    used[i] = true;
                    set.add(nums[i]);
                    temp[index] = nums[i];
                    recurtion(nums, used, index + 1, len, res, temp);
                    used[i] = false;
                }
            }
            return res;
        }
}

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/109668588