1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class Solution { public: void combination(string digits, vector<vector<char> >chars, vector<string>& ans, int len, int cur,int nums[], int sequence[], bool isUsed[][4]) { for(int i = 0;i < nums[digits[cur] - '0'];i++) { if(isUsed[cur][i] == false) { isUsed[cur][i] = true; vector<char> temp = chars[digits[cur] - '0' - 2]; sequence[cur] = temp[i]; if(cur == digits.length() - 1) { string str = ""; for(int j = 0;j < digits.length();j++) { str += sequence[j]; } ans.push_back(str); } else { combination(digits, chars, ans, len, cur + 1, nums, sequence, isUsed); } isUsed[cur][i] = false; } } }
vector<string> letterCombinations(string digits) { vector<string> ans; if(digits.length() == 0) { return ans; } vector<vector<char> >chars; int nums[10] = {0, 0, 3, 3, 3, 3, 3, 4, 3, 4}; int index = 0; for(int i = 2;i < 10;i++) { vector<char> temp; for(int j = 0;j < nums[i];j++, index++) { char ch = 'a' + index; temp.push_back(ch); } chars.push_back(temp); } bool isUsed[digits.length()][4] = {{0}}; int sequence[digits.length()] = {0}; combination(digits, chars, ans, digits.length(), 0, nums, sequence, isUsed); return ans; } };
|