回溯与递归
-
map<char, string>my_map; void backTrack(vector<string>&combinations,string digits, int index,string &combination) { if (index == digits.size()) { combinations.push_back(combination); } string letters = my_map[digits[index]]; for (int i = 0; i < letters.size(); i++) { combination.push_back(letters[i]); backTrack(combinations, digits, index + 1, combination); combination.pop_back(); } } vector<string> letterCombinations(string digits) { my_map.insert(pair<char, string>('2', "abc")); my_map.insert(pair<char, string>('3', "def")); my_map.insert(pair<char, string>('4', "ghi")); my_map.insert(pair<char, string>('5', "jkl")); my_map.insert(pair<char, string>('6', "mno")); my_map.insert(pair<char, string>('7', "pqrs")); my_map.insert(pair<char, string>('8', "tuv")); my_map.insert(pair<char, string>('9', "wxyz")); vector<string>combinations; if (digits.empty()) { return combinations; } string combination; backTrack(combinations,digits, 0, combination); for (int i = 0; i < combinations.size(); i++) { cout << combinations[i] << endl; } return combinations; }
never never wait