Problem Link
In this problem we will be given a string of digits, as like old days featured phones. We have to generate the number of ways we can generate string if,
digit 2 = "abc"
digit 3 = "def"
....
digit 9 = "wxyz"
Solution idea:
we can use dfs approach for solve this.
Code:
class Solution {
public:
map<char,string>mm;
vector<string>vec;
void solve(string digits,int pos,string ans){
if(pos == digits.size()){
if(digits!="")vec.push_back(ans);
return;
}
for(auto it:mm[digits[pos]]){
ans.push_back(it);
solve(digits,pos+1,ans);
ans.pop_back();
}
}
vector<string> letterCombinations(string digits) {
mm['2'] = "abc";
mm['3'] = "def";
mm['4'] = "ghi";
mm['5'] = "jkl";
mm['6'] = "mno";
mm['7'] = "pqrs";
mm['8'] = "tuv";
mm['9'] = "wxyz";
solve(digits,0,"");
return vec;
}
};
No comments:
Post a Comment
If you have any doubts, let me know through comments