17. Letter Combinations of a Phone Number

1.問題

2.想法

3.程式碼

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if (digits.empty()) {
            return res;
        }
        vector<vector<char>> v;
        v.push_back({' '});
        v.push_back({' '});
        v.push_back({'a', 'b', 'c'});
        v.push_back({'d', 'e', 'f'});
        v.push_back({'g', 'h', 'i'});
        v.push_back({'j', 'k', 'l'});
        v.push_back({'m', 'n', 'o'});
        v.push_back({'p', 'q', 'r', 's'});
        v.push_back({'t', 'u', 'v'});
        v.push_back({'w', 'x', 'y', 'z'});
        int size = digits.size();
        string record = "";
        helper(v, digits, record, 0, res);
        
        return res;
    }
private:
    void helper(vector<vector<char>> v, string digits, string record, int startIndex, vector<string>& res){
        if (startIndex == digits.length()){
            res.push_back(record);
            return;
        }
        int index = (int)(digits[startIndex] - '0');
        for (int i = 0; i < v[index].size(); i++) {
            record.push_back(v[index][i]);
            helper(v, digits, record, startIndex + 1, res);
            record.pop_back();
        }
    }
};

Last updated