Leetcode 17 Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could 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"].

循环:输入数字数{每个之前组成的字符串+{每个该次输入数字对应的字母}}

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

这里使用了两个变量交替更新,更省空间。

def letter_combinations(digits)

    letter = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']

    return [] if digits == ''

    a = ['']

    digits.chars.each do |x|

        b = []

        a.each {|y| letter[x.to_i].chars.each {|c| b << y+c } }

        a = b

    end

    a

end

 

递归:记载当前已生成的字符串

def letter_combinations(digits)

    @letter = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']

    return [] if digits == ''

    @ans = []

    comb('',digits,0)

    @ans

end



def 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

你可能感兴趣的:(LeetCode)