17. Letter Combinations of a Phone Number

JJ·2021년 1월 5일
0

Algorithms

목록 보기
50/114
class Solution {
    List<String> result = new ArrayList<String>();
    Map<Character, String> m = new HashMap<Character, String>();
    public List<String> letterCombinations(String digits) {
        if (digits.length() == 0) {
            return result;
        }
        m.put('2', "abc");
        m.put('3', "def");
        m.put('4', "ghi");
        m.put('5', "jkl");
        m.put('6', "mno");
        m.put('7', "pqrs");
        m.put('8', "tuv");
        m.put('9', "wxyz");
        
        helper(digits, "");
        
        return result;
      
    }
    
    public void helper(String digits, String comb) {
        if (digits.length() == 0) result.add(comb);
        else {
            if (digits.charAt(0) == '7' || digits.charAt(0) == '9') {
            helper(digits.substring(1), comb + m.get(digits.charAt(0)).substring(0, 1));
            helper(digits.substring(1), comb + m.get(digits.charAt(0)).substring(1, 2));
            helper(digits.substring(1), comb + m.get(digits.charAt(0)).substring(2, 3));
            helper(digits.substring(1), comb + m.get(digits.charAt(0)).substring(3, 4));
            } else if (m.containsKey(digits.charAt(0))) {
            helper(digits.substring(1), comb + m.get(digits.charAt(0)).substring(0, 1));
            helper(digits.substring(1), comb + m.get(digits.charAt(0)).substring(1, 2));
            helper(digits.substring(1), comb + m.get(digits.charAt(0)).substring(2, 3));
            }
            
        }
        
    }
}

Runtime: 1 ms, faster than 79.50% of Java online submissions for Letter Combinations of a Phone Number.
Memory Usage: 38.4 MB, less than 65.46% of Java online submissions for Letter Combinations of a Phone Number.

재귀를 썼읍니다.. 근데 진심 더러운 코드

?? 더 좋은 방법이 있을 것 같아서 답지를 봤는데 제꺼랑 똑같네요.. 그리고 믿기지 않지만 이게 backtracking이라는 점???? 근데 댓글에서는 backtracking이 아니라 재귀라고 말하고 있네욥

오늘은 혼자 푼 문제가 3문제나 되서 행복하네요 ㅎㅎ

0개의 댓글