Leetcode 17 Letter Combinations of a Phone Number
2015-06-14 19:51
537 查看
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.
循环:输入数字数{每个之前组成的字符串+{每个该次输入数字对应的字母}}
这里使用了两个变量交替更新,更省空间。
递归:记载当前已生成的字符串
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
相关文章推荐
- C++ 容器元素的存储和获取
- PHP 错误与异常 笔记与总结(10)错误处理器测试
- CentOS 5.5 DHCP服务器配置
- CSS3知识点
- 堆和栈的区别
- app客户端与服务器数据交互时—数据加密
- Android自定义控件_自定义属性format详解
- 【翻译自mos文章】找到持有library cache lock session的方法
- 【C++沉思录】代理类
- 果园监控
- leetcode--Path Sum II
- 黑马程序元----集合框架
- c++ const关键字总结
- 对身边的人
- 面向对象程序设计
- 【学习笔记】【C语言】break和continue
- keep pool优化
- Android头像上传/拍照/从相册选择Demo(个人信息模块会用到)
- Linux的inode的理解
- Android开源图表库: