leetcode || 140、Word Break II

problem:

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

Hide Tags
  Dynamic Programming Backtracking

thinking:

1 使用二维表vector<vector<int> >tbl记录,记录从i点,能否跳到下一个break位置。如果不能,那么tbl[i]就为空。如果可以,就记录可以跳到哪些位置。
2 利用二维表优化递归回溯法。
优化点:
如果当前位置是start,但是tbl[start]为空,那么就是说,这个break位置不能break整个s串的,直接返回上一层,不用搜索到下一层了。


code:

class Solution {
public:
	vector<string> wordBreak(string s, unordered_set<string> &dict) 
	{
		vector<string> rs;
		string tmp;
		vector<vector<int> > tbl = genTable(s, dict);
		word(rs, tmp, s, tbl, dict);
		return rs;
	}
	void word(vector<string> &rs, string &tmp, string &s, vector<vector<int> > &tbl,
		unordered_set<string> &dict, int start=0)
	{
		if (start == s.length())
		{
			rs.push_back(tmp);
			return;
		}
		for (int i = 0; i < tbl[start].size(); i++)
		{
			string t = s.substr(start, tbl[start][i]-start+1);
			if (!tmp.empty()) tmp.push_back(' ');
			tmp.append(t);
			word(rs, tmp, s, tbl, dict, tbl[start][i]+1);
			while (!tmp.empty() && tmp.back() != ' ') tmp.pop_back();//tmp.empty()
			if (!tmp.empty()) tmp.pop_back();
		}
	}
	vector<vector<int> > genTable(string &s, unordered_set<string> &dict)
	{
		int n = s.length();
		vector<vector<int> > tbl(n);
		for (int i = n - 1; i >= 0; i--)
		{
			if(dict.count(s.substr(i))) tbl[i].push_back(n-1);
		}
		for (int i = n - 2; i >= 0; i--)
		{
			if (!tbl[i+1].empty())//if we can break i->n
			{
				for (int j = i, d = 1; j >= 0 ; j--, d++)
				{
					if (dict.count(s.substr(j, d))) tbl[j].push_back(i);
				}
			}
		}
		return tbl;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值