LeetCode笔记 139.单词拆分

问题描述:

在这里插入图片描述

思路分析:

一开始想的是简单粗暴的用DFS解决,然后提交代码发现超出时间限制了,只通过了29个用例=。=,后来改成用动态规划的思想。

代码:

/*动态规划*/
class Solution
{
public:
	bool wordBreak(string s, vector<string>& wordDict)
	{
		vector<bool> flag(s.size() + 1, false);
		flag[0] = true;

		for (int i = 1; i < s.size() + 1; i++)
		{
			for (int j = 0; j < i; j++)
			{
				if (flag[j] && inDict(s.substr(j, i - j), wordDict))
				{
					flag[i] = true;
				}
			}
		}

		return flag.back();
	}

	bool inDict(string s, vector<string> wordDict)
	{
		for (auto x : wordDict)
		{
			if (x == s)
			{
				return true;
			}
		}
		return false;
	}
};

/*DFS 超出了时间限制*/
class Solution {
public:
	bool wordBreak(string s, vector<string>& wordDict) {
		bool result = false;

		DFS(s, wordDict, result);

		return result;
	}

	void DFS(string s, vector<string>& wordDict, bool &result)
	{
		if (s == "")
		{
			result = true;
			return;
		}
			
		string str;
		for (int i = 0; i < wordDict.size(); i++)
		{
			if (result == true)  break;

			str = s.substr(0, wordDict[i].size());
			if (str == wordDict[i])
			{
				str = s.substr(wordDict[i].size(), s.size() - wordDict[i].size());
				DFS(str, wordDict, result);
			}
		}
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值