My iterative solution:


  • 0
    N

    class Solution {
    public:
    vector<string> letterCombinations(string digits) {
    vector<string> results;
    if (digits == "") return results;
    char first[10] = {' ', ' ', 'a', 'd', 'g', 'j', 'm', 'p', 't', 'w'};
    int length[10] = {0, 0, 3, 3, 3, 3, 3, 4, 3, 4};
    string result = digits;
    for (int i = 0; i < digits.length(); ++i) {
    result[i] = first[digits[i] - '0'];
    }
    results.push_back(result);
    int i = digits.length() - 1;
    while (i >= 0) {
    if (result[i] - first[digits[i] - '0'] < length[digits[i] - '0'] - 1) {
    result[i]++;
    results.push_back(result);
    while(i < digits.length() - 1) ++i;
    } else {
    result[i] = first[digits[i] - '0'];
    --i;
    }
    }
    return results;
    }
    };


Log in to reply
 

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