forked from aylei/leetcode-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn0078_subsets.rs
71 lines (64 loc) · 1.4 KB
/
n0078_subsets.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
/**
* [78] Subsets
*
* Given a set of distinct integers, nums, return all possible subsets (the power set).
*
* Note: The solution set must not contain duplicate subsets.
*
* Example:
*
*
* Input: nums = [1,2,3]
* Output:
* [
* [3],
* [1],
* [2],
* [1,2,3],
* [1,3],
* [2,3],
* [1,2],
* []
* ]
*
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn subsets(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut res = Vec::new();
Solution::backtrack(0, vec![], &nums, &mut res);
res
}
fn backtrack(start: usize, mut curr: Vec<i32>, nums: &Vec<i32>, result: &mut Vec<Vec<i32>>) {
if start >= nums.len() {
result.push(curr);
return
}
// current element dropped
Solution::backtrack(start+1, curr.clone(), nums, result);
// current element picked
curr.push(nums[start]);
Solution::backtrack(start+1, curr, nums, result);
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_78() {
assert_eq!(
Solution::subsets(vec![]),
vec![vec![]]
);
assert_eq!(
Solution::subsets(vec![1]),
vec![vec![],vec![1]]
);
assert_eq!(
Solution::subsets(vec![1,2]),
vec![vec![],vec![2],vec![1],vec![1,2]]
);
}
}