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.
这是回溯问题(参考:http://blog.csdn.net/jarvischu/article/details/16067319)。
下面是JavaScript代码编写的递归版和迭代版的代码:
递归版: var letterCombinations = function(digits) { var map = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']; var result = []; backtrack(map, "", digits, result, 0); return result; }; function backtrack(map, s, digits, result, start){ if(digits.length === 0) return; if(s.length === digits.length){ result.push(s); return; } else{ for(var i = start; i < digits.length; i++){ var index = digits[i] - '0'; for(var j=0; j < map[index].length; j++){ s = s + map[index][j]; backtrack(map, s, digits, result, i+1); s = s.substring(0, s.length-1); } } } }