-
Notifications
You must be signed in to change notification settings - Fork 0
/
permutations.rs
66 lines (52 loc) · 1.66 KB
/
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
use std::collections::HashSet;
/// Given an array `nums` of distinct integers, return all the possible permutations. You can
/// return the answer in any order.
struct Solution;
impl Solution {
fn backtrack(results: &mut Vec<Vec<i32>>, nums: &Vec<i32>, current: Vec<i32>, seen: HashSet<i32>) {
let n = nums.len();
let c = current.len();
if n == c {
results.push(current);
} else {
for num in nums {
if !seen.contains(&num) {
let mut new_current = current.clone();
new_current.push(*num);
let mut new_seen = seen.clone();
new_seen.insert(*num);
Self::backtrack(results, nums, new_current, new_seen);
}
}
}
}
pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut results = Vec::new();
let current = Vec::new();
let seen = HashSet::new();
Self::backtrack(&mut results, &nums, current, seen);
results
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn example_1() {
let nums = vec![1,2,3];
let result = Solution::permute(nums);
assert_eq!(result, vec![vec![1,2,3], vec![1,3,2], vec![2,1,3], vec![2,3,1], vec![3,1,2], vec![3,2,1]]);
}
#[test]
fn example_2() {
let nums = vec![0,1];
let result = Solution::permute(nums);
assert_eq!(result, vec![vec![0,1], vec![1,0]]);
}
#[test]
fn example_3() {
let nums = vec![1];
let result = Solution::permute(nums);
assert_eq!(result, vec![vec![1]]);
}
}