-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0046_permutations.rs
More file actions
51 lines (45 loc) · 1.14 KB
/
s0046_permutations.rs
File metadata and controls
51 lines (45 loc) · 1.14 KB
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
#![allow(unused)]
pub struct Solution {}
// amazon interview
impl Solution {
fn backtrack(n: usize, nums: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>, start: usize) {
if start == n {
ans.push(nums.clone());
return;
}
for i in start..nums.len() {
Self::swap(nums, start, i);
Self::backtrack(n, nums, ans, start + 1);
Self::swap(nums, start, i);
}
}
fn swap(nums: &mut Vec<i32>, start: usize, end: usize) {
let t = nums[start];
nums[start] = nums[end];
nums[end] = t;
}
pub fn permute(mut nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut ans = vec![];
let n = nums.len();
Self::backtrack(n, &mut nums, &mut ans, 0);
ans
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_46() {
assert_eq!(
Solution::permute(vec![1, 2, 3]),
vec![
vec![1, 2, 3],
vec![1, 3, 2],
vec![2, 1, 3],
vec![2, 3, 1],
vec![3, 2, 1],
vec![3, 1, 2],
]
);
}
}