Skip to content

Commit 87bbb42

Browse files
authored
Merge pull request #1189 from voski/add-17-letter-combinations-of-a-phone-number-for-ruby
add #17 Letter Combinations of a Phone Number for ruby
2 parents e3aaf4b + 9a01085 commit 87bbb42

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Diff for: ruby/17-Letter-Combinations-Of-A-Phone-Number.rb

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
$MAP = {
2+
2 => %w(a b c),
3+
3 => %w(d e f),
4+
4 => %w(g h i),
5+
5 => %w(j k l),
6+
6 => %w(m n o),
7+
7 => %w(p q r s),
8+
8 => %w(t u v),
9+
9 => %w(w x y z)
10+
}
11+
12+
# @param {String} digits
13+
# @return {String[]}
14+
def letter_combinations(digits)
15+
ans = []
16+
17+
recurse(digits, "", ans, 0) unless digits.empty?
18+
19+
ans
20+
end
21+
22+
def recurse(digits, prefix, ans, i)
23+
if digits.length == prefix.length
24+
ans << prefix
25+
return
26+
end
27+
28+
digit = digits[i].to_i
29+
30+
$MAP[digit].each do |c|
31+
recurse(digits, prefix + c, ans, i + 1)
32+
end
33+
end

0 commit comments

Comments
 (0)