Leetcode 17 Letter Combinations of a Phone Number, leetcode
Given a digit string, return all possible letter combinations that the number coshould represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Cycle: Enter the number of digits {each character string consisting of the previous + {each letter corresponding to the entered number }}
def letter_combinations(digits) letter = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz'] return [] if digits == '' ans = [['']] digits.chars.each do |x| ans << [] ans[-2].each do |y| letter[x.to_i].chars.each {|c| ans[-1] << y+c} end end ans[-1]end
Recursion: records the currently generated string
def letter_combinations(digits) @letter = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz'] return [] if digits == '' @ans = [] comb('',digits,0) @ansenddef comb(str,digits,i) @ans << str if str.length == digits.length @letter[digits[i].to_i].chars.each {|x| comb(str+x,digits,i+1)}end