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.
解题思路:
使用DFS算法,JAVA实现如下:
static String[] alpha = new String[] { " ","1", "abc", "def","ghi", "jkl", "mno","pqrs", "tuv", "wxyz" }; static StringBuilder sb = new StringBuilder(); static void dfs(List<String> list, String digits, int cur) { if (cur >= digits.length()) list.add(sb.toString()); else { for (int i = 0; i < alpha[digits.charAt(cur) - ‘0‘].length(); i++) { sb.append(alpha[digits.charAt(cur) - ‘0‘].charAt(i)); dfs(list, digits, cur + 1); sb.deleteCharAt(sb.length() - 1); } } } static public List<String> letterCombinations(String digits) { List<String> list = new ArrayList<String>(); if (digits.length()==0) return list; dfs(list, digits, 0); return list; }
思路二:
凡是用到递归的地方都能用循环解决,因此可以用循环算法,JAVA实现如下:
static public List<String> letterCombinations(String digits) { List<String> list = new ArrayList<String>(); String[] alpha = new String[] { " ","1", "abc", "def","ghi", "jkl", "mno","pqrs", "tuv", "wxyz" }; if (digits.length()==0) return list; int[] number = new int[digits.length()];//存储每次遍历字符位置 int index = 0; while(index>=0) { StringBuilder sb = new StringBuilder(); for(int i=0; i<digits.length(); i++) sb.append(alpha[digits.charAt(i)-‘0‘].charAt(number[i])); list.add(sb.toString()); // 每回合需要重置index到末尾 index = digits.length()-1; while(index>=0) { if( number[index] < (alpha[digits.charAt(index)-‘0‘].length()-1) ) { number[index]++; break; } else { number[index] = 0; index--; } } } return list; }
时间: 2024-10-25 09:52:48