티스토리 뷰

https://leetcode.com/problems/letter-combinations-of-a-phone-number/

 

Letter Combinations of a Phone Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

[leetcode][C++][Java] letter combinations of a phone number

 

 

 

 

C++

class Solution {
public:
    string arr[10] = { "","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };

    void dfs(int n, string digits, string s, vector<string> &ret) {
        if (n == digits.size()) {
            ret.push_back(s);
            return;
        }

        int arri = digits[n] - '0';
        for (char c : arr[arri]) {
            s.push_back(c);
            dfs(n + 1, digits, s, ret);
            s.pop_back();
        }
    }

    vector<string> letterCombinations(string digits) {
        vector<string> ret;
        if (!digits.empty())
            dfs(0, digits, "", ret);
        return ret;
    }
};

 

 

 

 

Java

class Solution {
    private String[] phone = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

    public void dfs(char[] arr, int n, String s, List<String> ans) {
        if (n == arr.length) {
            ans.add(s);
            return;
        }

       for (char c : phone[arr[n] - '0'].toCharArray()) {
            s += c;
            dfs(arr, n + 1, s, ans);
            s = s.substring(0, s.length() - 1);
        }
    }    
    
    public List<String> letterCombinations(String digits) {
        List<String> ans = new ArrayList<>();
        if(digits.length() == 0) return ans;
        
        char[] arr = digits.toCharArray();
        dfs(arr, 0, "", ans);      
        
        return ans;
    }
}
댓글