0
点赞
收藏
分享

微信扫一扫

[Leetcode] 动态规划类java题解

毅会 2022-05-04 阅读 38

139. 单词拆分

public class WordBreak {

    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> wordSet = new HashSet<String>(wordDict);
        boolean[] dp = new boolean[s.length() + 1];  //Boolean会抛空指针
        dp[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] && wordSet.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }
    
}

152. 乘积最大子数组

class Solution {
     public int maxProduct(int[] nums) {

        int  n = nums.length;
        int[] dp = new int[n];
        dp[0]=nums[0];
        int result  = nums[0], nmax = nums[0], nmin = nums[0];
        for(int i = 1;i<n;i++){
            int temp1 = nmax*nums[i], temp2 = nmin*nums[i];
            nmax = Math.max(Math.max(temp1, temp2), nums[i]);
            nmin = Math.min(Math.min(temp1, temp2), nums[i]);
            result = Math.max(nmax, result);

        }
        return result;

    }
}
举报

相关推荐

0 条评论