#include<iostream>
using namespace std;
#include<vector>
#include<string>
class Solution {
public:
vector<string> letterCombinations(string digits)
{
vector<string> res = { "" };
vector<string>_num = { "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxzy" };
vector<string> mark; //定义一个空的vector作为digits长度为0时的输出!
int nl = digits.size();
if (nl < 1) return mark;
for (int i = 0; i < nl; i++)
{
vector<string> temp; //定义一个temp记录当前的结果,但是每一次循环都要初始为空!
int ng = digits[i] - '1';
for (int j = 0; j < _num[ng].length(); j++)
{
for (int k = 0; k < res.size(); k++)
{
temp.push_back(res[k] + _num[ng][j]);
}
}
res.swap(temp); //不断累加res!
}
return res;
}
};
刷题总结:
这道题采用了不断叠加的方法,意思是通过用前面算出的可能性再和后一个按键进行组合,所以用一个res和temp不断交换进行叠加!注意当digits为空时,返回空的vector!