17. 电话号码的字母组合
递归
class Solution {
List<String> ls;
String[] arr = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
public List<String> letterCombinations(String digits) {
ls = new ArrayList<String>();
ls.clear();
if (digits != null && digits.length() > 0)
dfs( digits, "");
return ls;
}
public void dfs( String num, String res) {
if (num.length() == 0)
ls.add(res);
else {
int flag = num.charAt(0) - '0';
for (int i = 0; i < arr[flag].length(); i++) {
dfs( num.substring(1), res + arr[flag].charAt(i));
}
}
}
}
循环
class Solution {
String[] arr = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
public List<String> letterCombinations(String digits) {
List<String> ls = new ArrayList<String>();
ls.clear();
if (digits != null && digits.length() > 0) {
ls.add("");
for(int i = 0 ; i < digits.length() ;i++) {
List<String> temp = new ArrayList<String>();
for(int x = 0 ; x < arr[digits.charAt(i)-'0'].length() ;x++) {
for(String y : ls) {
temp.add(y+arr[digits.charAt(i)-'0'].charAt(x));
}
}
ls = temp;
}
}
return ls;
}
}