|
| 1 | +// 77. Combinations |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/combinations/ |
| 5 | +// |
| 6 | +// Tags: Backtracking |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Use an internal function that iterates over all digits between the last |
| 11 | + /// digit added plus one and n adding each of them and checking the length |
| 12 | + /// of the resulting vector, if the vector has length k, add it to the |
| 13 | + /// result, otherwise call itself to add the next digit. |
| 14 | + /// |
| 15 | + /// Time complexity: O(k^n) - We iterate over k digit, for each digit, the |
| 16 | + /// decision tree branches into n options. |
| 17 | + /// Space complexity: O(k^n) - Each call to add_digit will add a new digit |
| 18 | + /// to the result and we saw the number of calls in the time complexity. |
| 19 | + /// |
| 20 | + /// Runtime 7 ms Beats 85.74% |
| 21 | + /// Memory 2.83 MB Beats 72.88% |
| 22 | + pub fn combine(n: i32, k: i32) -> Vec<Vec<i32>> { |
| 23 | + let mut res = vec![]; |
| 24 | + fn add_digit(cur: &mut Vec<i32>, res: &mut Vec<Vec<i32>>, l: usize, n: usize, k: usize) { |
| 25 | + for i in l..=n { |
| 26 | + cur.push(i as i32); |
| 27 | + if cur.len() == k { |
| 28 | + res.push(cur.clone()); |
| 29 | + } else { |
| 30 | + add_digit(cur, res, i + 1, n, k); |
| 31 | + } |
| 32 | + cur.pop(); |
| 33 | + } |
| 34 | + } |
| 35 | + let mut cur = vec![]; |
| 36 | + add_digit(&mut cur, &mut res, 1, n as usize, k as usize); |
| 37 | + res |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +// Tests. |
| 42 | +fn main() { |
| 43 | + let tests = [ |
| 44 | + ( |
| 45 | + 4, |
| 46 | + 2, |
| 47 | + vec![ |
| 48 | + vec![1, 2], |
| 49 | + vec![1, 3], |
| 50 | + vec![1, 4], |
| 51 | + vec![2, 3], |
| 52 | + vec![2, 4], |
| 53 | + vec![3, 4], |
| 54 | + ], |
| 55 | + ), |
| 56 | + (1, 1, vec![vec![1]]), |
| 57 | + ]; |
| 58 | + for t in tests { |
| 59 | + assert_eq!(Solution::combine(t.0, t.1), t.2); |
| 60 | + } |
| 61 | + println!("[92m» All tests passed![0m") |
| 62 | +} |
0 commit comments