Easy 0ms C++ recursion, easy to understand.


  • 0
    S
    class Solution {
    public:
    	vector<string> s;
    	unordered_map<char, vector<char>> maps;
    	Solution(){
    		maps['2'] = vector<char>{ 'a','b','c' };
    		maps['3'] = vector<char>{ 'd','e','f' };
    		maps['4'] = vector<char>{ 'g','h','i' };
    		maps['5'] = vector<char>{ 'j','k','l' };
    		maps['6'] = vector<char>{ 'm','n','o' };
    		maps['7'] = vector<char>{ 'p','q','r','s' };
    		maps['8'] = vector<char>{ 't','u','v' };
    		maps['9'] = vector<char>{ 'w','x','y','z' };
    	}
    	
    	void recurse(string digits, int digit, int letter, string st) {
    		if (st.length() == digits.length()) {
    			s.push_back(st);
    			return;
    		}
    		if (digit > digits.size())
    			return;
    		if (letter > maps[digits[digit]].size())
    			return;
    		for(int i=0;i<maps[digits[digit]].size();i++)
    			recurse(digits,digit+1, i, st + maps[digits[digit]][i]);
    	}
    	vector<string> letterCombinations(string digits) {
    	    if(!digits.length())
    	        return s;
    		recurse(digits, 0, 0, "");
    		return s;
    	}
    };
    

Log in to reply
 

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