代码随想录算法训练营第二十一天| 216.组合总和III 17.电话号码的字母组合
216.组合总和III
思路:
很像上一个组合类型的题目,唯一不同的就是自己写一个sum
代码:
1 void convertBST_cur(TreeNode* root, vector<TreeNode*>& nodes) 2 { 3 if (!root) return ; 4 if (root->left) convertBST_cur(root->left, nodes); 5 nodes.push_back(root); 6 if (root->right) convertBST_cur(root->right, nodes); 7 } 8 TreeNode* convertBST(TreeNode* root) { 9 if (!root) return nullptr; 10 11 stack<TreeNode*> selected; 12 selected.push(root); 13 vector<TreeNode*> nodes; 14 convertBST_cur(root, nodes); 15 16 //如果更改它们的值,那么就会导致链接出现了问题 17 for (int i = nodes.size() - 2; i >= 0; i--) 18 { 19 nodes[i]->val += nodes[i + 1]->val; 20 } 21 22 return root; 23 }
17.电话号码的字母组合
思路:
较为简单,只是对相同的数组之间的循环
代码:
1 void letterCombinations_trackBack(map<char, vector<char>> charMap,int k, string digits,int startIndex, vector<char>&path, vector<string>&result) 2 { 3 if (path.size() == k) 4 { 5 string str; 6 str.assign(path.begin(), path.end()); 7 result.push_back(str); 8 return; 9 } 10 if (startIndex >= k) 11 { 12 return; 13 } 14 15 for (char i : charMap[digits[startIndex]]) 16 { 17 path.push_back(i); 18 //如何找到下一个应该的字符串? 19 letterCombinations_trackBack(charMap, k, digits, startIndex + 1, path, result); 20 path.pop_back(); 21 } 22 23 } 24 vector<string> letterCombinations(string digits) { 25 //构建数据集 26 std::map<char, std::vector<char>> charMap = { 27 {'0', {}}, 28 {'1', {}}, 29 {'2', {'a', 'b', 'c'}}, 30 {'3', {'d', 'e', 'f'}}, 31 {'4', {'g', 'h', 'i'}}, 32 {'5', {'j', 'k', 'l'}}, 33 {'6', {'m', 'n', 'o'}}, 34 {'7', {'p', 'q', 'r', 's'}}, 35 {'8', {'t', 'u', 'v'}}, 36 {'9', {'w', 'x', 'y', 'z'}} 37 }; 38 vector<char>path; 39 vector<string> result; 40 41 if (digits.size() == 0)return result; 42 letterCombinations_trackBack(charMap, digits.size(), digits, 0, path, result); 43 44 return result; 45 }