public class Solution {
public List<String> letterCombinations(String digits) {
String[] mapping = {"", "", "abc", "def", "ghi", "jkl", "mon", "pqrs", "tuv", "wxyz"};
List<String> res = new ArrayList<>();
if (digits == null || digits.length() == 0)
return res;
helper(0, digits, mapping, new StringBuilder(), res);
return res;
}
/**
* @param
* i, index of current digit
* digits, digits string
* mapping, a map between digtis and letters
* curr, a StringBuilde to save the path from first digit to last
* res, result list
*/
public void helper(int i, String digits, String[] mapping, StringBuilder curr, List<String> res) {
if (i == digits.length()) { // reache the end of digits, save the path to the result list
res.add(curr.toString());
return;
}
String str = mapping[digits.charAt(i)-'0'];
for (int k=0; k<str.length(); k++) {
curr.append(str.charAt(k)); // add current lettern to the path
helper(i+1, digits, mapping, curr, res); // move to next digit
curr.setLength(curr.length()-1); // finish a path, remove the previous letter from the StringBuilder
}
}
}
Leetcode 17. Letter Combinations of a Phone Number
最新推荐文章于 2020-03-26 17:35:13 发布