-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.rs
97 lines (89 loc) · 1.98 KB
/
main.rs
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
fn main() {
println!("Hello, world!");
}
struct Solution {}
impl Solution {
pub fn permute_unique(mut nums: Vec<i32>) -> Vec<Vec<i32>> {
nums.sort();
let mut n = nums.clone();
let mut res = vec![];
res.push(n.clone());
Self::next_permutation(&mut n);
while n != nums {
res.push(n.clone());
Self::next_permutation(&mut n);
}
res
}
pub fn next_permutation(nums: &mut Vec<i32>) {
if nums.len() <= 1 { return }
let mut i = nums.len() - 2;
while let false = nums[i] < nums[i + 1] {
if i != 0 {
i -= 1
} else {
nums.reverse();
return
}
}
let mut j = nums.len() - 1;
while let false = nums[i] < nums[j] {
j -= 1;
}
nums.swap(i, j);
nums[i+1..].reverse()
}
}
#[cfg(test)]
mod test {
use crate::*;
#[test]
fn basic() {
assert_eq!(
Solution::permute_unique(vec![1,1,2]),
vec![
vec![1,1,2],
vec![1,2,1],
vec![2,1,1]
]
);
}
#[test]
fn basic2() {
assert_eq!(
Solution::permute_unique(vec![1,1,1]),
vec![
vec![1,1,1]
]
);
}
#[test]
fn edge() {
assert_eq!(
Solution::permute_unique(vec![1]),
vec![
vec![1],
]
);
assert_eq!(
Solution::permute_unique(vec![]),
vec![
vec![],
]
);
}
#[test]
fn leetcode() {
assert_eq!(
Solution::permute_unique(vec![2,2,1,1]),
vec![
vec![1,1,2,2],
vec![1,2,1,2],
vec![1,2,2,1],
vec![2,1,1,2],
vec![2,1,2,1],
vec![2,2,1,1]
]
);
}
}