C++ Non-recursive no helper function concise solution using simple loops


  • 0

    For a digit string digits (length n), suppose we already have the result resfor substring of first n-1digits, then the result for ndigits is simply appending each mapped letter of digits[n-1]to res.

        vector<string> letterCombinations(string digits) {
          if (digits.empty()) return {};    
          vector<string> toChars = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 
          vector<string> res = {""};
          for (char c:digits) {
            auto s = toChars[c - '2']; int n = res.size();    
            for (int i = 0; i < s.length(); ++i) {
              for (int j = 0; j < n; ++j) {
                if (i == s.length()-1) res[j] += s[i];
                else res.push_back(res[j] + s[i]);
              }      
            }
          }
          return res;
        }
    

Log in to reply
 

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