Java Solution(Recursion)


  • 0
    G

    import java.util.*;

    class Solution {

    private List<String> list = new ArrayList<>();
    
    private String[] strings = {"", "", "abc", "def",
            "ghi", "jkl", "mno",
            "pqrs", "tuv", "wxyz"};
    
    public List<String> letterCombinations(String digits) {
        if (digits.length() < 1)
            return list;
        String s = strings[Integer.valueOf(digits.substring(0, 1))];
        String res = digits.substring(1, digits.length());
        for (int i = 0; i < s.length(); i++){
            list.add(s.substring(i, i + 1));
            letter(res);
        }
        return list;
    }
    
    private void letter(String str) {
        if (str.equals(""))
            return;
        int num = list.size() - 1;
        String current = list.get(num);
        list.remove(num);
        String s = str.substring(0, 1);
        String res = str.substring(1, str.length());
        String string = strings[Integer.valueOf(s)];
        for (int i = 0; i < string.length(); i++){
            list.add(current + string.substring(i, i + 1));
            letter(res);
        }
    }
    

    }


Log in to reply
 

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