Article Directory
Leetcode 17. Alphabet combination of phone numbers
Problem Description
Given numbers only a 2-9
string, it returns all letter combinations indicated. The mapping from numbers to letters is given below (same as phone keys). Note 1 does not correspond to any letter.
Problem solving report
Typical DFS.
- Set an index
index
to determine whetherdigits
the end has been searched . - In the
dfs()
interior, if you have todigits
end, this road will add the current generation of str to the result. - If it has not reached the
digits
end, loop through the characters that can be added in the next step and increase the indexindex
by 1.
Implementation code
class Solution{
public:
map<char, string> M = {
{'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"},
{'6', "mno"}, {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"}
};
vector<string> letterCombinations(string digits){
if(digits.size()==0) return {};
vector<string>ans;
dfs(ans, "", 0, digits);
return ans;
}
// 这个地方的 ans必须是值引用
void dfs(vector<string>&ans, string curStr, int index, string digits){
if(index==digits.size()) ans.push_back(curStr);
else{
for(int i=0;i<M[digits[index]].size();i++){
dfs(ans, curStr+M[digits[index]][i], index+1, digits);
}
}
}
};
References
[1] Leetcode 17. The letter combination of the phone number
Leetcode 22. Bracket generation
Problem Description
The number n represents the logarithm of generating parentheses. Please design a function for generating all possible and effective combinations of parentheses.
Problem solving report
Similar to the previous question, omitted.
Implementation code
class Solution{
public:
vector<string> generateParenthesis(int n){
if(n==0) return {};
vector<string>ans;
dfs(ans, "", n,0);
return ans;
}
// 这个地方的 ans必须是值引用
void dfs(vector<string>&ans, string target, int open, int close){
if(open==0&&close==0) ans.push_back(target);
else{
if(open>0) dfs(ans, target+'(', open-1, close+1);
if(close>0) dfs(ans, target+')', open, close-1);
}
}
};