http://oj.leetcode.com/problems/word-break/
动态规划题目,重点是建立出模型来:
fun(start,end) = fun(start,i)*fun(i+1,end);
二维动态数组的申请:
int len = s.length();
int **flag = new int *[len];
for(int i = 0;i<len;i++)
flag[i] = new int [len];
#include <iostream> #include <string> #include <unordered_set> using namespace std; class Solution { public: bool fun(string s,unordered_set<string> &dict,int start,int end,int **flag) { if(flag[start][end]==1) return true; if(flag[start][end]==-1) return false; string subString = s.substr(start,end-start+1); if(dict.find(subString)!=dict.end()) return true; for(int i = start;i<end;i++) if(fun(s,dict,start,i,flag)*fun(s,dict,i+1,end,flag)) { flag[start][end] = 1; return 1; } flag[start][end] = -1; return false; } bool wordBreak(string s, unordered_set<string> &dict) { int len = s.length(); int **flag = new int *[len]; for(int i = 0;i<len;i++) flag[i] = new int [len]; return fun(s,dict,0,len-1,flag); } }; int main() { class Solution mys; string s = "leetcode"; unordered_set<string> dict; dict.insert("le"); //dict.insert("et"); dict.insert("code"); cout<<mys.wordBreak(s,dict); return 0; }