13-line C++ without digit-letter mapping


  • 1
    M
    class Solution {
    public:
        
        void dfs(string ds, int p, string& str, vector<string>& ans) {
            if (p==ds.length()) {
                ans.push_back(str);
                return;
            }
            
            int d=ds[p]-'0';
            for (int i=0; i< (d==9||d==7  ? 4:3); i++) {
                str[p]=(char) ('a'+ (d-2)*3 + i + ((d>7)?1:0));
                dfs(ds, p+1, str, ans);
            }
        }
        
        vector<string> letterCombinations(string digits) {
            vector<string> ans;
            string str;
            int n=digits.length();
            
            if(n>0) {
                while(n--) str+= " ";
                dfs(digits, 0, str, ans);
            }
            return ans;
        }
    };

Log in to reply
 

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