My backtracking solution using java


  • 0
    L

    public class Solution {
    public List<String> letterCombinations(String digits) {
    List<String> result = new LinkedList<>();
    String[] meaning = new String[]{"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    if(digits.length() == 0) return result;
    StringBuilder sb = new StringBuilder();
    backtrack(result, sb, 0, digits, meaning);
    return result;
    }
    public void backtrack(List<String> result, StringBuilder sb, int index, String digits, String[] meaning)
    {
    if(index >= digits.length())
    {
    result.add(new String(sb.toString()));
    return;
    }
    int tmp = digits.charAt(index) - '0';
    for(int i = 0; i < meaning[tmp].length(); i++)
    {
    sb.append(meaning[tmp].charAt(i));
    backtrack(result, sb, index + 1, digits, meaning);
    sb.deleteCharAt(sb.length() - 1);
    }
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.