forked from aylei/leetcode-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths0046_permutations.rs
70 lines (64 loc) · 1.46 KB
/
s0046_permutations.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
/**
* [46] Permutations
*
* Given a collection of distinct integers, return all possible permutations.
*
* Example:
*
*
* Input: [1,2,3]
* Output:
* [
* [1,2,3],
* [1,3,2],
* [2,1,3],
* [2,3,1],
* [3,1,2],
* [3,2,1]
* ]
*
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/permutations/
// discuss: https://leetcode.com/problems/permutations/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
if nums.len() <= 1 {
return vec![nums];
}
nums.iter()
.flat_map(|&num| {
let mut sub = nums.clone().into_iter().filter(|&x| x != num).collect();
Solution::permute(sub)
.into_iter()
.map(|vec| {
let mut vec = vec;
vec.push(num);
vec
})
.collect::<Vec<Vec<i32>>>()
})
.collect()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_46() {
assert_eq!(
Solution::permute(vec![1, 2, 3]),
vec![
vec![3, 2, 1],
vec![2, 3, 1],
vec![3, 1, 2],
vec![1, 3, 2],
vec![2, 1, 3],
vec![1, 2, 3],
]
)
}
}