Skip to content

Commit 9b3b2e5

Browse files
committed
feat(backtracking): add 78_subsets.rs
1 parent bd4a3a2 commit 9b3b2e5

File tree

2 files changed

+45
-4
lines changed

2 files changed

+45
-4
lines changed

README.md

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ flowchart LR
1919
linked_list("Linked List")
2020
trees("Trees")
2121
tries("Tries")
22-
backtracing("Backtracing")
22+
backtracking("Backtracking")
2323
%% heap("Heap")
2424
heap("Heap / Priority Queue")
2525
graphs("Graphs")
@@ -42,11 +42,11 @@ flowchart LR
4242
linked_list --> trees
4343
4444
trees --> tries
45-
trees --> backtracing
45+
trees --> backtracking
4646
trees --> heap
4747
48-
backtracing --> dp
49-
backtracing --> graphs
48+
backtracking --> dp
49+
backtracking --> graphs
5050
5151
dp --> bit
5252
dp --> math
@@ -139,3 +139,9 @@ so that you can use `just tf TEST` command to test.
139139
| 226. Invert Binary Tree | Easy | [226_invert_binary_tree.rs](./tests/226_invert_binary_tree.rs) |
140140
| 104. Maximum Depth of Binary Tree | Easy | [104_maximum_depth_of_binary_tree.rs](./tests/104_maximum_depth_of_binary_tree.rs) |
141141
| 102. Binary Tree Level Order Traversal | Medium | [102_binary_tree_level_order_traversal.rs](./tests/102_binary_tree_level_order_traversal.rs) |
142+
143+
### Backtracking
144+
145+
| Problem | Difficulty | Solution |
146+
| - | - | - |
147+
| 78. Subsets | Medium | [78_subsets.rs](./tests/78_subsets.rs) |

tests/78_subsets.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// 78. Subsets
2+
// https://leetcode.com/problems/subsets/description/
3+
// Topics: Backtracking.
4+
// Difficulty: Medium.
5+
6+
#[test]
7+
fn test_78_subsets() {}
8+
9+
#[derive(Debug)]
10+
pub struct Solution;
11+
12+
// ---------------------------------
13+
// copy to leetcode starts from here
14+
// ---------------------------------
15+
16+
impl Solution {
17+
pub fn subsets(nums: Vec<i32>) -> Vec<Vec<i32>> {
18+
let result: Vec<Vec<i32>> = vec![vec![]];
19+
recursion(result, nums).0
20+
}
21+
}
22+
23+
fn recursion(mut v: Vec<Vec<i32>>, mut nums_left: Vec<i32>) -> (Vec<Vec<i32>>, Vec<i32>) {
24+
let Some(num) = nums_left.pop() else {
25+
return (v, nums_left);
26+
};
27+
let mut new_v = vec![];
28+
for item in v.iter() {
29+
let mut item = item.clone();
30+
item.push(num);
31+
new_v.push(item);
32+
}
33+
v.append(&mut new_v);
34+
recursion(v, nums_left)
35+
}

0 commit comments

Comments
 (0)