-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path47.permutations-ii.go
77 lines (69 loc) · 1.74 KB
/
47.permutations-ii.go
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import "sort"
/*
* @lc app=leetcode id=47 lang=golang
*
* [47] Permutations II
*
* https://leetcode.com/problems/permutations-ii/description/
*
* algorithms
* Medium (46.58%)
* Likes: 2089
* Dislikes: 63
* Total Accepted: 366.7K
* Total Submissions: 785.5K
* Testcase Example: '[1,1,2]'
*
* 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]
* ]
*
*
*/
// @lc code=start
func permuteUnique(nums []int) [][]int {
return permuteUnique1(nums)
}
func permuteUnique1(nums []int) [][]int {
sort.Ints(nums)
output, track, visit := [][]int{}, []int{}, make([]bool, len(nums))
backtrack(&output, nums, track, visit, 0)
return output
}
func backtrack(output *[][]int, nums, track []int, visited []bool, index int) {
if len(track) == len(nums) {
path := make([]int, len(nums))
copy(path, track)
*output = append(*output, path)
return
}
for i := 0; i < len(nums); i++ {
if visited[i] {
continue
}
// https://leetcode.com/problems/permutations-ii/discuss/18594/Really-easy-Java-solution-much-easier-than-the-solutions-with-very-high-vote
// With inputs as [1a, 1b, 2a],
/// If we don't handle the duplicates, the results would be: [1a, 1b, 2a], [1b, 1a, 2a]...,
// so we must make sure 1a goes before 1b to avoid duplicates
// By using nums[i-1]==nums[i] && !used[i-1], we can make sure that 1b cannot be choosed before 1a
if i > 0 && nums[i-1] == nums[i] && !visited[i-1] {
continue
}
track = append(track, nums[i])
visited[i] = true
backtrack(output, nums, track, visited, index+1)
track = track[:len(track)-1]
visited[i] = false
}
}
// @lc code=end