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.node
Given "23"
Return ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
git
DFS作法:
在主函數中,建立手機按鍵的String array,建立StringBuilder sb,建立結果數組res.
在helper函數中,用index去標記原字符串digits中正被遍歷的那一位。
當index到達最後一位,也就是digits.length()的時候:若是此時StringBuilder長度非0,就加入結果數組res。
不然,找出當前位在table中的對應字符串cur,而後遍歷cur的每一位:每一位的字符放入sb,調用helper函數,再刪除最末位繼續遍歷。數組
public class Solution { public List<String> letterCombinations(String digits) { List<String> res = new ArrayList<>(); String[] table = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; StringBuilder sb = new StringBuilder(); helper(digits, 0, table, sb, res); return res; } public void helper(String digits, int index, String[] table, StringBuilder sb, List<String> res) { if (index == digits.length()) { if (sb.length() != 0) res.add(sb.toString()); } else { String cur = table[digits.charAt(index)-'0']; for (int i = 0; i < cur.length(); i++) { sb.append(cur.charAt(i)); helper(digits, index+1, table, sb, res); sb.deleteCharAt(sb.length()-1); } } } }
public class Solution { public List<String> letterCombinations(String digits) { //format output List<String> res = new ArrayList<>(); //input null/empty checks if (digits == null || digits.length() == 0) return res; //create the num-to-char mapping String[] map = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; //initialize an empty string representing a subset String str = ""; //call DFS dfs(digits, 0, map, str, res); return res; } public void dfs(String digits, int index, String[] map, String str, List<String> res) { //stop the path when such condition met if (str.length() == digits.length()) res.add(str); //DFS implementation else { //get node String cur = map[digits.charAt(index)-'0']; //exhaustive search for (int i = 0; i < cur.length(); i++) { //visit and select the current node str += cur.charAt(i); //use index+1 to DFS the next node dfs(digits, index+1, map, str, res); //backtracking to traverse the unvisited nodes str = str.substring(0, str.length()-1); } } } }