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”].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
s思路:
1. 需要列举所有情况,一般都是for+recursive来实现backtracking。这道题,相当于排列组合。
class Solution {
private:
vector<string> letters={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public:
void helper(vector<string>&res,string&digits,string cur,int idx){
if(idx==digits.size()){
res.push_back(cur);
return;
}
for(int i=0;i<letters[digits[idx]-'0'].size();i++){
cur+=letters[digits[idx]-'0'][i];
helper(res,digits,cur,idx+1);
cur.pop_back();//跟pop相关的操作不需要跟操作符!
}
}
vector<string> letterCombinations(string digits) {
//
if(digits.empty()) return vector<string>(0);
vector<string> res;
helper(res,digits,"",0);
return res;
}
};