#What is dumb about this approach?

4 messages · Page 1 of 1 (latest)

wispy lark
#

So I was trying to solve LeetCode 17: Letter Combinations of a Phone number. It seemed straightforward to me so I tried this:

class Solution {
public:
    std::vector<std::string> answer; // For our answer
    std::unordered_map<char, std::vector<char>> keyMap; //Map char range to vec of chars
    
    vector<string> letterCombinations(string digits) 
    {
        //Hanle blanks
        if(digits == "") {return {};}
        
        // Generate a map
        keyMap['2'] = {'a','b','c'};
        keyMap['3'] = {'d','e','f'};
        keyMap['4'] = {'g','h','i'};
        keyMap['5'] = {'j','k','l'};
        keyMap['6'] = {'m','n','o'};
        keyMap['7'] = {'p','q','r','s'};
        keyMap['8'] = {'t','u','v'};
        keyMap['9'] = {'w','x','y','z'};
        
        // If only one digit pressed
        if(digits.size() == 1)
        {
            for(auto& ch: keyMap[digits[0]])
            {
                answer.push_back(std::string(1,ch));
            }   
            return answer;
        }

        // Otherwise use backtracking (more like DFS) to build all combinations
        backtrack(0,"",digits); 
        return answer;
    }

    void backtrack(int index, std::string currentString,std::string digits)
    {   //Base case
        if(index == digits.size())
        {
            answer.push_back(currentString);
            return;
        }

        //Recursive case
        for(auto ch: keyMap[digits[index]])
        {
            //currentString += ch;
            backtrack(index+1, currentString+ch, digits);
        }

    }

    
};```

It resulted in a bottom of the pile solution 😦 
What did I miss? I thought I was clever mapping stuff and doing DFS based recursions!!
spiral scaffoldBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

limpid cosmos
#

Too many unnecessary memory allocations and recursion is hiding many unnecessary operations that are happening behind curtains.

covert flower
#

better suited for code review but here's what I'll say

  • the maximum size of the vector will be 4^digit len, so you can optimize that at the beginning
  • when passing into backtrack, use std::string_view&
  • similar question posted in #code-golf earlier, you could see what they're doing there