Created
January 29, 2022 19:48
-
-
Save anil477/fc75262efeffabb57551bca66facc448 to your computer and use it in GitHub Desktop.
17. Letter Combinations of a Phone Number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
// 17. Letter Combinations of a Phone Number | |
// https://leetcode.com/problems/letter-combinations-of-a-phone-number/ | |
// https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8109/My-recursive-solution-using-Java/222635 | |
private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; | |
public List<String> letterCombinations(String digits) { | |
List<String> ret = new LinkedList<String>(); | |
if (digits.length() == 0) | |
return ret; | |
combination(new StringBuilder(), digits, 0, ret); | |
return ret; | |
} | |
private void combination(StringBuilder prefix, String digits, int offset, List<String> ret) { | |
if (offset >= digits.length()) { | |
ret.add(prefix.toString()); | |
return; | |
} | |
String letters = KEYS[(digits.charAt(offset) - '0')]; | |
for (int i = 0; i < letters.length(); i++) { | |
prefix.append(letters.charAt(i)); | |
combination(prefix, digits, offset + 1, ret); | |
prefix.deleteCharAt(prefix.length() - 1); | |
} | |
} | |
/* | |
https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8109/My-recursive-solution-using-Java/222635 | |
Using String - | |
private void combination(String prefix, String digits, int offset, List<String> ret) { | |
if (offset >= digits.length()) { | |
ret.add(prefix); | |
return; | |
} | |
String letters = KEYS[(digits.charAt(offset) - '0')]; | |
for (int i = 0; i < letters.length(); i++) { | |
combination(prefix + letters.charAt(i), digits, offset + 1, ret); | |
} | |
} | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment