LeetCode-140 单词拆分 II

17 篇文章 0 订阅
15 篇文章 0 订阅

单词拆分 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;
}
};

在这里插入图片描述
实在是没办法改进了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值