139. 单词拆分(中等)
class Solution {public boolean wordBreak(String s, List<String> wordDict) {boolean dp[] = new boolean[s.length()+1];dp[0] = true;for(int i=1;i<=s.length();i++){for(String word:wordDict){if(i-word.length()>=0){String cur = s.substring(i-word.length(),i);if(cur.equals(word)){dp[i] = dp[i-word.length()]|dp[i];}}}}return dp[s.length()];}
}
198. 打家劫舍(中等)
注意:对长度为 2 的时候进行特判
class Solution {public int rob(int[] nums) {if(nums.length>=2)nums[1] = Math.max(nums[0],nums[1]);for(int i=2;i<nums.length;i++){nums[i] = Math.max(nums[i-1],nums[i-2]+nums[i]);}return nums[nums.length-1];}
}
213. 打家劫舍 II(中等)
思路:选择 0~n-2 或者选择1~n-1
public int rob(int[] nums) {int n = nums.length;if(n<=2)return Arrays.stream(nums).max().getAsInt();int dp0[] = new int[n-1]; // 取 0int dp[] = new int[n]; // 不取 0dp0[0] = nums[0];dp0[1] = Math.max(nums[0],nums[1]);dp[1] = nums[1];dp[2] = Math.max(nums[1],nums[2]);for(int i=2;i<n-1;i++){int j = i+1;dp0[i] = Math.max(dp0[i-1],dp0[i-2]+nums[i]);dp[j] = Math.max(dp[j-1],dp[j-2]+nums[j]);}return Math.max(dp0[n-2],dp[n-1]);}