博文中会简要介绍Leetcode P0139题目分析及解题思路。
“Word Break”这道题是比较典型的一维费用背包问题,这类问题的一般思路是动态规划解决。
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
一维费用背包问题属于比较经典的动态规划问题。在这里s
的长度可以看作背包的容量,wordDict
中每个单词的长度可以看作物品的费用。与背包问题的差异在于,这个问题只需要知道是否存在一种选取方法,使得wordDict
中选取的词能够拼接并且恰好和s
相等。这道题的递推表达式如下,
以下是Java的题解代码实现。
以下是C++的题解代码实现。