[Leetcode 47] 17 Letter Combinations of a Phone Number

Problem:

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

 

Analysis:

This is a simple backtracking problem. Backtrack method view the solution sapce as a tree. And it will go down from the root(initial state) to the leaf(some solution) to build a solution for the problem. A general structure of a backtracking program is as follows:

void backtrack(p1, ..., pn) {

  if (current solution is a well formed solution) {

    //do something

    return;

  }

  for every child of current node

    backtrack()

 

}

 

With this in mind, the problem is easy to solve.

 

Code:

 1 class Solution {
 2 public:
 3             vector<string> table;
 4             vector<string> res;
 5 
 6     vector<string> letterCombinations(string digits) {
 7         // Start typing your C/C++ solution below
 8         // DO NOT write int main() function
 9         if (digits.size() == 0) 
10             return vector<string>(1,"");
11         
12         res.clear();
13         table.resize(10);
14         table[2] = "abc";
15         table[3] = "def";
16         table[4] = "ghi";
17         table[5] = "jkl";
18         table[6] = "mno";
19         table[7] = "pqrs";
20         table[8] = "tuv";
21         table[9] = "wxyz";    
22         
23         backtrack(digits, 0, "");
24         return res;
25     }
26     
27     void backtrack(string &s, int pos, string ss) {
28         if (pos == s.size()) {
29             res.push_back(ss);
30             return ;
31         }
32         
33         for (int i=0; i<table[s[pos] - '0'].size(); i++) {
34             backtrack(s, pos+1, ss+table[s[pos] - '0'][i]);
35         }
36         
37         return ;
38     }
39 };
View Code

 

Attention:

There are many C++ skills used in this code, learn it.

posted on 2013-05-25 13:08  freeneng  阅读(135)  评论(0编辑  收藏  举报

导航