【leetcode】17.(Medium) Letter Combinations of a Phone Number
阿新 • • 發佈:2018-11-19
解題思路:
回溯
提交程式碼:
class Solution {
public List<String> letterCombinations(String digits) {
List<String> res=new ArrayList<String>();
if(digits.length()==0) return res;
String basestr= "";
findCombination(res,digits,0,basestr);
return res;
}
public void findCombination(List<String> res,
String digits,int p,String basestr) {
//res:result digits:the input digits string
//p:the position of char in digits
String[] chars= {
"0","1","abc","def","ghi","jkl",
"mno","pqrs","tuv","wxyz"
};
if(p==digits.length()) {
res.add(basestr);
return;
}
int index=digits.charAt(p)-'0';
for(int i=0;i<chars[index].length();i++) {
basestr+=chars[index].charAt(i);
findCombination(res,digits,p+1,basestr);
basestr=basestr.substring(0, p);
}
}
}
執行結果: