单词拆分 II【php版】

47 篇文章 1 订阅

在这里插入图片描述

<?php
class Solution {

	private $memo = [];
	private $ans = [];
	/**
	 * @param String $s
	 * @param String[] $wordDict
	 * @return String[]
	 */
	function wordBreak($s, $wordDict) {
		$dict = array_flip($wordDict);
		$this->deepSearch($s, 0, $dict);
		return $this->ans;
	}

	/**
	 * 深度优先遍历
	 * @param $s
	 * @param $i
	 * @param $dict
	 */
	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;
					// i==0时,递归回溯到字串开头,此时的rear便是一条满足题意的记录,将其加入结果数组中
					if ($i == 0) {
						$this->ans[] = implode(' ', $rear);
					}
				}
			}
			// 将从i开始搜索的结果保存在memo中,以免重复计算
			$this->memo[$i] = $collection;
		}
		return $this->memo[$i];
	}
}

$s = new Solution();
var_dump($s->wordBreak("pineapplepenapple", ["apple", "pen", "applepen", "pine", "pineapple"]));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值