-
Notifications
You must be signed in to change notification settings - Fork 0
/
39_combination_sum.rb
44 lines (36 loc) · 1013 Bytes
/
39_combination_sum.rb
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
# frozen_string_literal: true
# https://leetcode.com/problems/combination-sum/
# @param {Integer[]} candidates
# @param {Integer} target
# @return {Integer[][]}
def combination_sum(candidates, target)
combine_sum(candidates, target, [], [])
end
private
# @param {Integer[]} candidates
# @param {Integer} target
# @param {Integer[][]} result
# @param {Integer[]} curr
# @return {Integer[][]}
def combine_sum(candidates, target, result, curr)
find_combination(candidates, target, 0, result, curr)
result
end
# @param {Integer[]} candidates
# @param {Integer} target
# @param {Integer} start
# @param {Integer[][]} result
# @param {Integer[]} curr
# @return {Void}
def find_combination(candidates, target, start, result, curr)
if target.zero?
result << curr.dup
return
end
return if target.negative?
(start...candidates.length).each do |i|
curr << candidates[i]
find_combination(candidates, target - candidates[i], i, result, curr)
curr.delete_at(curr.length - 1)
end
end