From 6bd5f5314241ad4e4faa71b2848fb2ccb2b18766 Mon Sep 17 00:00:00 2001 From: utkr07 Date: Wed, 5 Oct 2022 23:59:58 +0530 Subject: [PATCH] Added the solution of 'Letter Combinations of Phone Number' in medium folder --- Medium/ word-break.cpp | 59 +++++++++++++----------- Medium/LetterCombinationsPhoneNumber.cpp | 39 ++++++++++++++++ 2 files changed, 70 insertions(+), 28 deletions(-) create mode 100644 Medium/LetterCombinationsPhoneNumber.cpp diff --git a/Medium/ word-break.cpp b/Medium/ word-break.cpp index 5f7fd53..ddca61e 100644 --- a/Medium/ word-break.cpp +++ b/Medium/ word-break.cpp @@ -1,32 +1,35 @@ -class Solution { +class Solution +{ public: - - - bool solve(int i,set&st , string &target,int m, vector&dp) { - - if(i==m) return true ; - - if(dp[i] != -1) return dp[i] ; - - string temp = "" ; - for(int j = i ; j &st, string &target, int m, vector &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& wordDict) { - - setst ; - for(auto x : wordDict) st.insert(x) ; - int m = s.size() ; - vectordp(m+1,-1) ; - return solve(0,st,s,m,dp) ; - + + bool wordBreak(string s, vector &wordDict) + { + + set st; + for (auto x : wordDict) + st.insert(x); + int m = s.size(); + vector dp(m + 1, -1); + return solve(0, st, s, m, dp); } }; diff --git a/Medium/LetterCombinationsPhoneNumber.cpp b/Medium/LetterCombinationsPhoneNumber.cpp new file mode 100644 index 0000000..2e0c93d --- /dev/null +++ b/Medium/LetterCombinationsPhoneNumber.cpp @@ -0,0 +1,39 @@ +// 17. Letter Combinations of a Phone Number + +class Solution +{ +private: + void solve(string digit, string output, int index, vector &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 letterCombinations(string digits) + { + vector 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; + } +}; \ No newline at end of file