Timeline
Timeline
2025-11-27
init
Backtracking
Problem:
Backtracking
1234567891011121314151617181920212223242526272829303132333435363738394041424344 | using std::vector;using std::string;using std::unordered_map;const string digit2alpha[] = { [0] = { "" }, [1] = { "" }, [2] = { "abc" }, [3] = { "def" }, [4] = { "ghi" }, [5] = { "jkl" }, [6] = { "mno" }, [7] = { "pqrs" }, [8] = { "tuv" }, [9] = { "wxyz" } };class Solution { public: void backtrace(string &digits, string &track, vector<string> &res) { if (track.size() == digits.size()) { res.push_back(track); return; } string curr_alpha; char ch = digits[track.size()]; int i; curr_alpha = digit2alpha[ch - '0']; for (i = 0; i < curr_alpha.size(); i++) { // // Skip already selected to avoid duplicates // if (track.find(curr_alpha[i]) != string::npos) { // continue; // } // Add to selection track.push_back(curr_alpha[i]); // Enter the next level of the decision tree backtrace(digits, track, res); // Undo selection track.pop_back(); } } vector<string> letterCombinations(string digits) { vector<string> res; string track; backtrace(digits, track, res); return res; }}; |
leetcode hot100 rewrite
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 | using std::vector;using std::string;class Solution { private: vector<vector<char> > num2char = { {}, {}, { 'a', 'b', 'c' }, { 'd', 'e', 'f' }, { 'g', 'h', 'i' }, { 'j', 'k', 'l' }, { 'm', 'n', 'o' }, { 'p', 'q', 'r', 's' }, { 't', 'u', 'v' }, { 'w', 'x', 'y', 'z' }, }; void __letterCombinations(vector<int> &nums, vector<string> &res, string &curr, int pos) { int i, n = nums.size(); if (curr.size() == n) { res.push_back(curr); return; } for (char ch : num2char[nums[pos]]) { curr.push_back(ch); __letterCombinations(nums, res, curr, pos + 1); curr.pop_back(); } } public: vector<string> letterCombinations(string digits) { vector<string> res; vector<int> nums; string curr; for (char ch : digits) nums.push_back(ch - '0'); __letterCombinations(nums, res, curr, 0); return res; }}; |
