Skip to content

Add C++ code for Problem 17 #46

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions C++/17.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
Problem 17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive,
return all possible letter combinations that the number could represent.
Return the answer in any order.

https://leetcode.com/problems/letter-combinations-of-a-phone-number/
*/

class Solution {
public:
string mp[10] = {
"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
};

void helper(int st, string digits, vector<string>& ans) {
if(st == digits.length()) {
ans.push_back(digits);
return;
}
char temp = digits[st];
string vals = mp[temp - '0'];
for(int i = 0; i < vals.length(); i++) {
digits[st] = vals[i];
helper(st+1, digits, ans);
}
digits[st] = temp;
}

vector<string> letterCombinations(string digits) {
vector<string> ans;
if(digits.length() > 0)
helper(0, digits, ans);
return ans;
}
};