
<?php
class Solution {
private $memo = [];
private $ans = [];
function wordBreak($s, $wordDict) {
$dict = array_flip($wordDict);
$this->deepSearch($s, 0, $dict);
return $this->ans;
}
function deepSearch($s, $i, $dict) {
if ($i == strlen($s)) {
return [[]];
}
if (!array_key_exists($i, $this->memo)) {
$collection = [];
for ($j=$i; $j<strlen($s); $j++) {
$front = substr($s, $i, $j-$i+1);
if (!array_key_exists($front, $dict)) {
continue;
}
$rears = $this->deepSearch($s, $j+1, $dict);
foreach ($rears as $rear) {
array_unshift($rear, $front);
$collection[] = $rear;
if ($i == 0) {
$this->ans[] = implode(' ', $rear);
}
}
}
$this->memo[$i] = $collection;
}
return $this->memo[$i];
}
}
$s = new Solution();
var_dump($s->wordBreak("pineapplepenapple", ["apple", "pen", "applepen", "pine", "pineapple"]));