1. Iterative Nested Loops (Hardcoded for length <= 4)
Intuition
Extract character sets for each digit. Based on digits.length, run 1, 2, 3, or 4 nested loops combining characters.
When to apply: Simple conceptual approach when constraint is strictly fixed at 4.
Algorithm
- If
digits.isEmpty(), return[]. - Based on length, execute 1 to 4 nested loops over mapped character sets.
- Append combined string to result.
#include <iostream>#include <vector>#include <string> using namespace std; class Solution {public: vector<string> letterCombinations(string digits) { if (digits.empty()) return {}; vector<string> map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; vector<string> result = {""}; for (char d : digits) { string letters = map[d - '0']; vector<string> temp; for (const string& prefix : result) { for (char c : letters) { temp.push_back(prefix + c); } } result = move(temp); } return result; }}; int main() { Solution sol; auto res = sol.letterCombinations("23"); for (const string& s : res) cout << s << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(4^N * N)— Generates all combinations directly. - Space complexity:
O(1)— Uses constant auxiliary space beyond result.