-
Notifications
You must be signed in to change notification settings - Fork 0
/
s0078_subsets.rs
88 lines (83 loc) · 2.48 KB
/
s0078_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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
struct Solution;
//leetcode submit region begin(Prohibit modification and deletion)
impl Solution {
pub fn subsets(nums: Vec<i32>) -> Vec<Vec<i32>> {
fn dfs(
cur: usize,
nums: &[i32],
n: usize,
path: &mut Vec<i32>,
result: &mut Vec<Vec<i32>>,
) {
use std::cmp::Ordering::*;
match cur.cmp(&n) {
Equal => result.push(path.to_vec()),
Less => {
path.push(nums[cur]);
dfs(cur + 1, nums, n, path, result);
path.pop();
dfs(cur + 1, nums, n, path, result);
}
Greater => {}
}
}
let n = nums.len();
let mut result = Vec::new();
let mut path = Vec::new();
dfs(0, &nums, n, &mut path, &mut result);
result
}
// 修改组合的代码,改变长度
#[allow(dead_code)]
pub fn subsets_from_combination(nums: Vec<i32>) -> Vec<Vec<i32>> {
let len = nums.len();
let mut result = Vec::new();
let mut path = Vec::with_capacity(len);
fn dfs(
nums: &[i32],
len: usize,
current_sum: i32,
target_len: usize,
last_index: usize,
path: &mut Vec<i32>,
result: &mut Vec<Vec<i32>>,
) {
use std::cmp::Ordering::*;
match path.len().cmp(&target_len) {
Equal => result.push(path.to_vec()),
Less => {
for i in last_index..len {
let num = nums[i];
path.push(num);
dfs(
nums,
len,
current_sum + num,
target_len,
i + 1,
path,
result,
);
path.pop();
}
}
Greater => {}
}
}
for i in 0..=len {
dfs(&nums, len, 0, i, 0, &mut path, &mut result);
}
result
}
}
//leetcode submit region end(Prohibit modification and deletion)
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let nums = vec![0];
let res = vec![vec![0], vec![]];
assert_eq!(Solution::subsets(nums), res);
}
}