Leetcode: Letter Combinations of a Phone Number

简单DFS

总结

第一次提交忘了 clear 向量

digits[i]-'0'-2 这种写法 work

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 using namespace std;
 5 vector<vector<char> >phone;
 6 vector<string> result;
 7 class Solution {
 8 public:
 9     void init() {
10         int count = 0;
11         for(int i = 1; i <= 8; i ++) {
12             vector<char> tmp;
13             for(int j = 0; j < 3; j ++) {
14                 tmp.push_back('a'+count);
15                 count++;
16             }
17             if(i == 6 || i == 8) {
18                 tmp.push_back('a'+count);
19                 count++;
20             }
21             phone.push_back(tmp);
22         }
23     }
24     void proceeds(string digits, const int &i, const int &n, string partial) {
25         if(i == n) {
26             result.push_back(partial);
27             return;
28         }
29         //cout << digits[i]-'0'-2 << endl;
30         for(int j = 0; j < phone[digits[i]-'0'-2].size(); j ++) {
31             proceeds(digits, i+1, n, partial+ phone[digits[i]-'0'-2][j]);
32         }
33 
34     }
35     vector<string> letterCombinations(string digits) {
36         result.clear();
37         phone.clear();
38         init();
39         proceeds(digits, 0, digits.size(), "");
40         return result;
41     }
42 };

 

posted @ 2013-11-17 19:58  SangS  阅读(444)  评论(0编辑  收藏  举报