forked from aylei/leetcode-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn0077_combinations.rs
76 lines (70 loc) · 1.54 KB
/
n0077_combinations.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] Combinations
*
* Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
*
* Example:
*
*
* Input: n = 4, k = 2
* Output:
* [
* [2,4],
* [3,4],
* [2,3],
* [1,2],
* [1,3],
* [1,4],
* ]
*
*
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn combine(n: i32, k: i32) -> Vec<Vec<i32>> {
let mut res: Vec<Vec<i32>> = Vec::new();
Solution::backtrack(1, n, k, vec![], &mut res);
res
}
fn backtrack(start: i32, end: i32, k: i32, curr: Vec<i32>, result: &mut Vec<Vec<i32>>) {
if k < 1 {
result.push(curr);
return
}
if end - start + 1 < k {
// elements is not enough, return quickly
return
}
for i in start..end+1 {
let mut vec = curr.clone();
vec.push(i);
Solution::backtrack(i+1, end, k-1, vec, result);
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_77() {
assert_eq!(
Solution::combine(4, 2),
vec![vec![1, 2], vec![1, 3], vec![1, 4], vec![2, 3], vec![2, 4], vec![3, 4]]
);
assert_eq!(
Solution::combine(1, 1),
vec![vec![1]]
);
let empty: Vec<Vec<i32>> = vec![];
assert_eq!(
Solution::combine(0, 1),
empty
);
assert_eq!(
Solution::combine(2, 1),
vec![vec![1], vec![2]]
);
}
}