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.
给定一个字符串s和单词字典dict,在s中添加空格来构造所有字都在字典中的句子。
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"].
思路和前一题相同,使用动态规划
array(''),
);
for ($i = 1; $i <= $sNum; $i ++) {
for ($j = 0; $j < $i; $j ++) {
if ($j == 0) {
$subS = substr($s, -1 * $i);
} else {
$subS = substr($s, -1 * $i,-1 * $j);
}
if (in_array($subS, $dict) && isset($A[$j])) {
foreach ($A[$j] as $value) {
$A[$i][] = $subS.' '.$value;
}
}
}
}
return $A[$sNum];
}
}
$str = 'helloiamame';
$dict = array(
'hello','i','am','ame',
);
$objSolution = new Solution();
$ret = $objSolution->wordBreak($str, $dict);
print_r($ret);