-
题目: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”].
-
idea:
- 首先建立一个二维矩阵match来记录字符串中的字串是否在dict里,如match[i][j]表示字串i…j是否在dict里。
- 从字符串结尾处开始逆序遍历,如果begin到end在字典里,则判断0到begin是否也是一个句子。如果end==-1,那么cur_str就是一个句子,将cur_str添加到ans;否则不是一个句子,不用添加到ans
- 使用cur_str记录当前string,如果begin到end的字串属于dict,则push_back到cur_str。递归返回后,需要将cur_str使用pop_back(),尝试下一种可能性。
-
code
#include <bits/stdc++.h>
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
vector<string> ans;
const size_t len = s.size();
bool **match = (bool**)malloc(sizeof(bool*)*len);
for (int i = 0; i < len; i++){
//match[i] = (bool*)malloc(sizeof(bool)*len);
match[i] = new bool[len];
}
/*
make the match matrix, in which match[i][j] represents whether substring of s
from i to j is a word of dict
*/
for (int i = 0; i < len; i++){
for (int j = i; j < len; j++){
if (dict.find(s.substr(i, j-i+1)) != dict.end())
match[i][j] = true;
else match[i][j] = false;
}
}
vector<string> cur_str;
//make sentences according to the match matrix recursively.
make_sentence(s, len-1, ans, match, cur_str);
return ans;
}
void make_sentence(string s, int end, vector<string> &ans, bool **match, vector<string> &cur_str){
if (end<0){
unsigned len = cur_str.size();
string sentence = cur_str[0];
for (int i = 1; i < len; i++){
sentence = cur_str[i] + " " + sentence;
}
ans.push_back(sentence);
return;
}
for (int begin = end; begin>-1; --begin){
if (match[begin][end]){
cur_str.push_back(s.substr(begin, end-begin+1));
make_sentence(s, begin-1, ans, match, cur_str);
cur_str.pop_back();
}
}
}
};