leetcode.cn 17.电话号码的字母组合 - 生成组合数

这题难度标为“中等”,那肯定不难。看完题,知道就是生成组合数。

想起当年上学的时候我还做过一个组合工具类。于是在磁盘上搜索,找到一看,原来当年是Java写的一个类,代码也很简单。于是我用C++把这题打完了,核心部分也就二十行左右代码。

 1 const string DIGITS[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
 2 int indexs[8];
 3 bool mynext(const char *str, int n) {
 4     indexs[n - 1]++;
 5     for (int i = n - 1; i > 0; i--) {
 6         int len = DIGITS[str[i] - '2'].length();
 7         if (indexs[i] >= len) {
 8             indexs[i - 1]++;
 9             indexs[i] = 0;
10         }
11     }
12     return (indexs[0] < DIGITS[str[0] - '2'].length());
13 }
14 
15 class Solution {
16 public:
17     vector<string> letterCombinations(string digits) {
18         char ch[5];
19         vector<string> ans;
20         int n = digits.size();
21         if (n == 0) {
22             return ans;
23         }
24         ch[n] = 0;
25         memset(indexs, 0, sizeof(indexs));
26         do {
27             for (int i = 0; i < n; i++) {
28                 ch[i] = DIGITS[digits[i] - '2'][indexs[i]];
29             }
30             ans.push_back(string(ch));
31         } while (mynext(digits.c_str(), n));
32         return ans;
33     }
34 };

 

posted @ 2022-12-04 05:33  moonbay  阅读(19)  评论(0编辑  收藏  举报