problem:
Difficulty: medium
Description:
Full arrangement, but there are repeated elements, and each element is only used once, and all non-repeated arrangements are required to be returned.
Subject link: https://leetcode.com/problems/permutations-ii/
Related algorithms:
[Codewar training]Permutations(String)(full arrangement): https://blog.csdn.net/qq_28033719/article/details/105860028
Input range:
1 <= nums.length <= 8
-10 <= nums[i] <= 10
Enter the case:
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]]
My code:
The full array obviously uses recursion + loop. If the element is not reused, use used to indicate that it has been used, and create a temporary storage table. If it is specific, a bunch of reference parameters will be passed, and it will be almost written.
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;
}
}