LeetCode Palindrome Partitioning

Palindrome Partitioning

  Total Accepted: 18645  Total Submissions: 71813 My Submissions

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]

思路:

这一题为什么没有想到深搜呢?一般要把所有答案都遍历一边的题目都需要深搜。
回顾题目word break 2.

Word Break II

   Total Accepted: 7703  Total Submissions: 50334 My Submissions

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"].

这一题采用深搜的话复杂度过高,原因是深搜的失败率过高。失败率过高的原因在于每个切割方法与切割点前后的字串都有关系。所以,最终答案采用了dp+dfs的策略。使用dp事先算出一个方向上(假设为是否能够到达终点)是否成功。再dfs时,再加上判断是否能够从起点到达分割点,就能够完成全部判断。
见http://blog.csdn.net/kiki_yu/article/details/24603089

代码:

class Solution {
public:
vector<vector<string> > partition(string s) {
		vector<vector<string> > ans;
		vector<string> cur;
		dfs(0, s.length(), s, cur, ans);
		return ans;
	}

	void dfs(int start, int depth,  string s, vector<string> & cur, vector<vector<string> > &ans) {
		if (start == depth) {
			ans.push_back(cur);
			return;
		}
		for (int i = start; i < depth; i++) {
			if (isPalindrome(s, start, i)) {
				cur.push_back(s.substr(start, i - start + 1));
				dfs(i + 1, depth, s, cur, ans);
				cur.pop_back();
			}
		}
	}

	bool isPalindrome(string s, int b, int e) {
		for (int i = b, j = e; i < j; i++, j--) {
			if (s[i] != s[j])
				return false;
		}
		return true;
	}
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值