单词拆分 II
跟别人的代码比起来可能会长一点儿
class Solution {
public:
bool isvalue(string s, string temp)
{
if (s == temp)
return true;
return false;
}
bool find_a(vector<string>& wordDict, string s)
{
if (find(wordDict.begin(), wordDict.end(), s) != wordDict.end())
return true;
else
return false;
}
void huisu(string s,string temp, vector<string>& wordDict,int& count,vector<string> &result)
{
if (s.empty())
{
++count;
temp.pop_back();
result.push_back(temp);
return;
}
int len = wordDict.size();
for (int i = 0; i<len; ++i)
{
int len_w = wordDict[i].size();
if (s.size() >= len_w)
{
if (isvalue(s.substr(0, len_w), wordDict[i]))
{
//temp = temp +;
huisu(s.substr(len_w),temp+s.substr(0, len_w) + " ", wordDict, count,result);
//temp = temp + s.substr(0, len_w) + " ";
}
}
}
}
bool wordBreak_1(string s, vector<string>& wordDict)
{
int len = s.size();
//整体思想不是很难就是处理的一些细节需要注意,我们使用dp[i]表示长度为i的
vector<int> dp(len + 1, 0);//首先把初始值都设定为0
dp[0] = 1;
for (int i = 1; i <= len; ++i)//从1到n进行遍历
{
for (int j = 0; j < i; ++j)//遍历每个小区域的dp是否满足条件
{
string temp = s.substr(j, i - j);//获得之后的片段
if (dp[j] && find_a(wordDict, temp))
{
dp[i] = true;
break;
}
}
}
return dp[len];
}
vector<string> wordBreak(string s, vector<string>& wordDict) {
//使用回溯法或者是动态规划的算法
int count = 0;
string temp;
vector<string> result;
if (wordBreak_1(s, wordDict))
huisu(s, temp, wordDict, count, result);
return result;
}
};
实在是没办法改进了