-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpermuteUnique.go
More file actions
37 lines (31 loc) · 834 Bytes
/
Copy pathpermuteUnique.go
File metadata and controls
37 lines (31 loc) · 834 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* https://leetcode.com/problems/permutations-ii/description/
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
*/
package lbacktracking
import "sort"
func permuteUnique(nums []int) [][]int {
sort.Ints(nums)
res := [][]int{}
var helper func(nums []int, start int, res *[][]int)
helper = func(nums []int, start int, res *[][]int) {
if len(nums)-1 == start {
*res = append(*res, append([]int{}, nums...))
}
for i := start; i < len(nums); i++ {
if i != start && nums[i] == nums[start] {
continue
}
nums[i], nums[start] = nums[start], nums[i]
helper(append([]int{}, nums...), start+1, res)
}
}
helper(nums, 0, &res)
return res
}