Well, a typical backtracking problem. Make sure is clear with the following three problems:
- What's a partial solution and when is it finished? ---in this problem, the partial solution is a combination and it's finished once it is of the same length as digits< /c1>.
- How do I find all the partial solutions? ---The following code, I use a nested for -loop to traverse all the possible starting elements for each digit.
- When to make recursive calls? ---in the following code, once a element is added to the partial solution, we call the function to generate the Remainin G elements recursively.
Of course, remember to recover to the previous status once a partial solution are done. The following code, line (comb.resize (Comb.length ()-1)) are for this purpose.
The following should be self-explanatory:)
1 classSolution {2 Public:3vector<string> Lettercombinations (stringdigits) {4 stringMp[] = {" "," ","ABC","def","Ghi","JKL","MnO","PQRS","TUV","WXYZ"};5vector<string>Res;6 if(Digits.empty ())returnRes;7 stringcomb;8Combinations (digits,0, MP, comb, res);9 returnRes;Ten } One Private: A voidCombinations (string& Digits,intStartstringMp[],string& Comb, vector<string>&Res) { - if(comb.length () = =digits.length ()) { - Res.push_back (comb); the return; - } - for(inti =0; I < (int) Mp[digits[start]-'0'].length (); i++) { -Comb + = (Mp[digits[start]-'0'][i]); +Combinations (digits, start +1, MP, comb, res); -Comb.resize (Comb.length ()-1); + } A } at};
Well, the above recursive backtracking solution is a typical solution. In fact, this problem can also is solved iteratively. Refer to this link for more information. I have rewritten the code below for your reference.
classSolution { Public: Vector<string> Lettercombinations (stringdigits) {Vector<string>Res; if(Digits.empty ())returnRes; stringMp[] = {" "," ","ABC","def","Ghi","JKL","MnO","PQRS","TUV","WXYZ"}; Res.push_back (""); for(inti =0; I < (int) Digits.length (); i++) { stringLetters = Mp[digits[i]-'0']; Vector<string>temp; for(intj =0; J < (int) Letters.length (); J + +) for(intK =0; K < (int) Res.size (); k++) Temp.push_back (Res[k]+Letters[j]); Swap (res, temp); } returnRes; }};
[Leetcode] letter combinations of a Phone number