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.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
和combination还有subset差不多。dfs里的传参,start避免重复 ([1,2],[2,1]),index避免出现自己遍历自己以及遍历digits的下一个元素([1,1])
Source
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> st = new ArrayList<String>();
String a = new String();
if(digits.length() == 0){
st.add(a); //***
return st;
}
String[] num = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
dfs(0, 0, digits, num, st, a);
return st;
}
public void dfs(int start, int index, String digits, String[] num, List<String> st, String a){
if(a.length() == digits.length()){
st.add(new String(a));
return ;
}
if(index >= digits.length()) return ;
String k = num[digits.charAt(index) - '0']; //***注意charAt返回是char型 要转为int型
for(int i = 0; i < k.length(); i++){
dfs(i + 1, index + 1, digits, num, st, a + k.charAt(i)); //传参时要传index + 1
}
}
}
Test
public static void main(String[] args){
String digits = "";
System.out.println(new Solution().letterCombinations(digits));
}