Skip to content
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

Added the solution of 'Letter Combinations of Phone Number in C++' in medium… #274

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
59 changes: 31 additions & 28 deletions Medium/ word-break.cpp
Original file line number Diff line number Diff line change
@@ -1,32 +1,35 @@
class Solution {
class Solution
{
public:


bool solve(int i,set<string>&st , string &target,int m, vector<int>&dp) {

if(i==m) return true ;

if(dp[i] != -1) return dp[i] ;

string temp = "" ;
for(int j = i ; j<m ; j++) {

temp += target[j] ;
if(st.count(temp))
if (solve(j+1 ,st,target,m,dp)) return dp[i] = 1 ;
bool solve(int i, set<string> &st, string &target, int m, vector<int> &dp)
{

if (i == m)
return true;

if (dp[i] != -1)
return dp[i];

string temp = "";
for (int j = i; j < m; j++)
{

temp += target[j];
if (st.count(temp))
if (solve(j + 1, st, target, m, dp))
return dp[i] = 1;
}
return dp[i] = 0;
}
return dp[i] = 0 ;

}


bool wordBreak(string s, vector<string>& wordDict) {

set<string>st ;
for(auto x : wordDict) st.insert(x) ;
int m = s.size() ;
vector<int>dp(m+1,-1) ;
return solve(0,st,s,m,dp) ;


bool wordBreak(string s, vector<string> &wordDict)
{

set<string> st;
for (auto x : wordDict)
st.insert(x);
int m = s.size();
vector<int> dp(m + 1, -1);
return solve(0, st, s, m, dp);
}
};
39 changes: 39 additions & 0 deletions Medium/LetterCombinationsPhoneNumber.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// 17. Letter Combinations of a Phone Number

class Solution
{
private:
void solve(string digit, string output, int index, vector<string> &ans, string mapping[])
{

// base case
if (index >= digit.length())
{
ans.push_back(output);
return;
}

int number = digit[index] - '0';
string value = mapping[number];

for (int i = 0; i < value.length(); i++)
{
output.push_back(value[i]);
solve(digit, output, index + 1, ans, mapping);
output.pop_back();
}
}

public:
vector<string> letterCombinations(string digits)
{
vector<string> ans;
if (digits.length() == 0)
return ans;
string output;
int index = 0;
string mapping[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
solve(digits, output, index, ans, mapping);
return ans;
}
};