From 8853e5a754797317793f3229b7fe8aa6fac918b1 Mon Sep 17 00:00:00 2001 From: Lavesh Verma Date: Sat, 22 Oct 2022 15:33:02 +0530 Subject: [PATCH] Word break problem --- Dynamic Programming/cpp/Word_break.cpp | 55 ++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Dynamic Programming/cpp/Word_break.cpp diff --git a/Dynamic Programming/cpp/Word_break.cpp b/Dynamic Programming/cpp/Word_break.cpp new file mode 100644 index 0000000..649cfa9 --- /dev/null +++ b/Dynamic Programming/cpp/Word_break.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + + #include + + int dp[305]; + + unordered_set s; + + bool helper(string& str, int i, int n) + { + + if(i == n) + { + return true; + } + + + if(dp[i] != -1) + { + return dp[i]; + } + + + for(int j = i; j < n; j++) + { + if(s.count(str.substr(i, j - i + 1))) + { + if(helper(str, j + 1, n)) + { + return dp[i] = true; + } + } + } + + + return dp[i] = false; + } + + bool wordBreak(string str, vector& wordDict) { + + int n = str.size(); + + + for(auto word : wordDict) + { + s.insert(word); + } + + + memset(dp, -1, sizeof(dp)); + + return helper(str, 0, n); + } +}; \ No newline at end of file