Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.4 kB
2
Indexable
Never
int c2i(char c)
{
    return c - '0';
}

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> result;
        if (digits.size() == 0)
            return result;
        
        vector<string> index_letter{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        int number_of_combination = 1;
        vector<int> run_index(digits.size(), 0);
        for (int i = 0; i < digits.size(); i++)
        {
            if (index_letter[c2i(digits[i])].size())
                number_of_combination *= index_letter[c2i(digits[i])].size();
        }
        
        int iterator = 0;
        while (iterator < number_of_combination)
        {
            string tmp_str = "";
            for (int i = 0; i < digits.size(); i++)
            {
                int index = c2i(digits[i]);
                tmp_str.push_back(index_letter[index][run_index[i]]);
            }
                
            result.push_back(tmp_str);
            
            run_index[run_index.size()-1] += 1;
            for (int i = run_index.size() - 2; i >= 0; i--)
            {
                if (run_index[i+1] >= index_letter[c2i(digits[i+1])].size())
                {
                    run_index[i+1] = 0;
                    run_index[i] += 1;
                }
            }
            iterator += 1;
        }
        return result;
    }
};