Skip to content

Commit 000c6e7

Browse files
committed
77. Combinations
1 parent c7f5966 commit 000c6e7

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
| 73 | Set Matrix Zeroes | [Ruby](./algorithms/ruby/0073-set-matrix-zeroes.rb) | Medium |
6060
| 74 | Search a 2D Matrix | [Ruby](./algorithms/ruby/0074-search-a-2d-matrix.rb) | Medium |
6161
| 76 | Minimum Window Substring | [Ruby](./algorithms/ruby/0076-minimum-window-substring.rb) | Hard |
62+
| 77 | Combinations | [Ruby](./algorithms/ruby/0077-combinations.rb) | Medium |
6263
| 80 | Remove Duplicates from Sorted Array II | [Ruby](./algorithms/ruby/0080-remove-duplicates-from-sorted-array-ii.rb) | Medium |
6364
| 82 | Remove Duplicates from Sorted List II | [Ruby](./algorithms/ruby/0082-remove-duplicates-from-sorted-list-ii.rb) | Medium |
6465
| 86 | Partition List | [Ruby](./algorithms/ruby/0086-partition-list.rb) | Medium |

algorithms/ruby/0077-combinations.rb

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# frozen_string_literal: true
2+
3+
# 77. Combinations
4+
# https://leetcode.com/problems/combinations
5+
# Medium
6+
7+
=begin
8+
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
9+
10+
You may return the answer in any order.
11+
12+
Example 1:
13+
Input: n = 4, k = 2
14+
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
15+
Explanation: There are 4 choose 2 = 6 total combinations.
16+
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.
17+
18+
Example 2:
19+
Input: n = 1, k = 1
20+
Output: [[1]]
21+
Explanation: There is 1 choose 1 = 1 total combination.
22+
23+
Constraints:
24+
* 1 <= n <= 20
25+
* 1 <= k <= n
26+
=end
27+
28+
# @param {Integer} n
29+
# @param {Integer} k
30+
# @return {Integer[][]}
31+
def combine(n, k)
32+
return (1..n).map { |i| [i] } if k == 1
33+
34+
i = n
35+
result = []
36+
37+
while i > 1
38+
result += combine(i - 1, k - 1).map { |tuple| tuple + [i] }
39+
i -= 1
40+
end
41+
42+
result
43+
end
44+
45+
# **************** #
46+
# TEST #
47+
# **************** #
48+
49+
require "test/unit"
50+
class Test_combine < Test::Unit::TestCase
51+
def test_
52+
assert_equal [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]].sort, combine(4, 2).sort
53+
assert_equal [[1]], combine(1, 1)
54+
end
55+
end

0 commit comments

Comments
 (0)