dp:单词拆分

本文讨论了如何使用动态规划和深度优先搜索解决LeetCode上的字符串分词问题。通过状态转移方程和递归搜索,分别实现了一个时间复杂度为O(n^2)和O(2^n)的解决方案。代码示例中展示了两种方法的实现,并给出了测试用例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode,
分析
设状态为 f(i),表示 s[0,i] 是否可以分词,则状态转移方程为
f(i) = any_of(f(j)&&s[j + 1, i] ∈ dict), 0 ≤ j < i

#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
#include <algorithm>
using namespace std;

bool dfs(string s, int start, const unordered_set<string> &dict)
{
	if (start == s.size())
		return true;

	for ( int i = start + 1; i <= s.size(); ++i)
	{
		//string str = s.substr(start, i - start);
		//cout << str << endl;
		if (std::find(dict.begin(), dict.end(), s.substr(start, i - start)) != dict.end())
			if(dfs(s, i, dict))
				return true;
	}
	return false;
}

//深搜,超时 时间复杂度 O(2^n),空间复杂度 O(n)
bool solution( string s, const unordered_set<string> &dict)
{
	return dfs(s, 0, dict);
}

// 动规,时间复杂度 O(n^2),空间复杂度 O(n) 
//f(i) = any_of(f(j)&&s[j + 1, i] ∈ dict), 0 ≤ j < i
int solution1(string s, const unordered_set<string> &dict)
{
	//长度为 n 的字符串有 n+1 个隔板
	vector<bool> vec(s.size() + 1, false);
	vec[0] = true;
	for ( int i = 1; i <= s.size(); ++i )
	{
		for ( int j = i - 1; j >= 0; --j )
		{
			if ( vec[j] && dict.find(s.substr(j, i - j)) != dict.end() )
			{
				vec[i] = true;
				break;
			}
		}
	}
	return vec[s.size()];
}

int main()
{
	cout << solution1("leetcode", { "leet", "code" }) << endl;			//true
	cout << solution1("applepenapple", { "apple", "pen" }) << endl;		//true
	cout << solution1("catsandog", 
		{ "cats", "dog", "sand", "and", "cat" }) << endl;				//false

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值