分割回文串【php版】

在这里插入图片描述

class Solution {
	private $rlt = [];
	private $ans = [];
	private $dp = null;
	/**
	 * 递归回溯+动态规划预处理
	 * @param String $s
	 * @return String[][]
	 */
	function partition($s) {
		$len = strlen($s);

		// 使用动态规划预处理$s, 获得所有从i到j字串是否是回文字串的结果数组
		$this->dp = array_fill(0, $len, array_fill(0, $len, true));

		for ($j=1; $j<$len; $j++) {
			for ($i=0; $i<$j; $i++) {
				$this->dp[$i][$j] = $this->dp[$i+1][$j-1] && $s[$i] == $s[$j];
			}
		}

		$this->dfs($s, 0);
		return $this->rlt;
	}

	function dfs($s, $i) {
		if ($i == strlen($s)) {
			$this->rlt[] = $this->ans;
		}
		for ($j=$i; $j<strlen($s); $j++) {
			if ($this->dp[$i][$j]) {
				array_push($this->ans, substr($s, $i, $j-$i+1));
				$this->dfs($s, $j+1);
				array_pop($this->ans);
			}
		}
	}
}

递归回溯+记忆化

class Solution {

	private $f = null;
	private $rlt = [];
	private $ans = [];
    
	function partition($s) {
		$this->dfsV2($s, 0);
		return $this->rlt;
	}

	function dfsV2($s, $i) {
		if ($i == strlen($s)) {
			$this->rlt[] = $this->ans;
		}
		for ($j=$i; $j<strlen($s); $j++) {
			if ($this->isPalindrome($s, $i, $j)) {
				array_push($this->ans, substr($s, $i, $j-$i+1));
				$this->dfsV2($s, $j+1);
				array_pop($this->ans);
			}
		}
	}

	function isPalindrome($s, $i, $j) {
		if (isset($this->f[$i][$j])) {
			return $this->f[$i][$j];
		}
		if ($i >= $j) {
			$this->f[$i][$j] = true;
			return true;
		} else if ($s[$i] == $s[$j]) {
			return $this->isPalindrome($s, $i+1, $j-1);
		} else {
			$this->f[$i][$j] = false;
			return false;
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值