1 class Solution { 2 public: 3 vector<vector<int>> combinationSum3(int k, int n) { 4 back_tracking(k, n, 1, 0); 5 return result; 6 } 7 private: 8 vector<vector<int>> result; 9 vector<int> tmp; 10 void back_tracking(int k, int n, int start, int sum){ 11 if(tmp.size() == k && sum == n){ 12 result.push_back(tmp); 13 } 14 for(int i = start; i <= 9; i++){ 15 tmp.push_back(i); 16 back_tracking(k, n, i+1, sum+i); 17 tmp.pop_back(); 18 } 19 } 20 };
1 class Solution { 2 private: 3 vector<string> result; 4 string path; 5 const string vec[8] = { 6 "abc", 7 "def", 8 "ghi", 9 "jkl", 10 "mno", 11 "pqrs", 12 "tuv", 13 "wxyz" 14 }; 15 void back_tracking(const string& digits, int start){ 16 if(start == digits.size()){ 17 result.push_back(path); 18 return; 19 } 20 int index = digits[start] - '2'; 21 string str = vec[index]; 22 for(int i = 0; i < str.size(); i++){ 23 path.push_back(str[i]); 24 back_tracking(digits, start + 1); 25 path.pop_back(); 26 } 27 28 } 29 public: 30 vector<string> letterCombinations(string digits) { 31 if(digits.size() == 0) return result; 32 back_tracking(digits, 0); 33 return result; 34 } 35 };