Ruby solution - DFS - recursion.


  • 0
    N
    # @param {String} digits
    # @return {String[]}
    def letter_combinations(digits)
    
      return [] if digits == ''
      
      mapping = ['0', '1', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
    
        str = ''
        solution = []
        find_combination(digits, str, solution, mapping)
    
        solution
    end
    
    def find_combination (digits, str, solution, mapping)
    
      if digits.length == 0
        solution.push(str)
        return
      end
      digit = digits[0].to_i
      new_digits = digits[1,digits.length-1]
    
      arr = mapping[digit].chars
      arr.each do |char|
        str = str + char
        find_combination(new_digits, str, solution, mapping)
        str = str[0,str.length-1]
      end
    
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.