代码随想录算法训练营 day 46: 139.单词拆分 ● 关于多重背包,你该了解这些! ● 背包问题总结篇!

58 阅读1分钟

139. Word Break

dp数组为布尔值的题目。排列问题所以要先遍历背包。 dp[i]为在字符串s的[0,i]子串,是否符合题目要求,即为字典内词的组合。 递推公式为:dp[i]在[j,i]子串为字典子串,且dp[i]为true时,dp[i]取true。 最后返回dp数组的最后一个元素。

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] dp = new boolean[s.length()+1];
        Set<String> myset = new HashSet<String>(wordDict);


        for(int i=0; i<dp.length; i++) {
            dp[i] = false;
        }
        dp[0] = true;
        for(int i=1; i<=s.length(); i++) {
            for(int j=0; j<i; j++) {
                //word j-i
                String word = s.substring(j,i);
                if(myset.contains(word) && dp[j]) {
                    dp[i] = true;
                    break;
                } 
            }
        }

        return dp[s.length()];
        
    }
}