1 public class LEET_213 { 2 public int rob(int[] nums) { 3 if (nums == null || nums.length == 0) { 4 return 0; 5 } 6 int n = nums.length; 7 if (n == 1) { 8 return nums[0]; 9 } 10 return Math.max(rob(nums, 0, n - 2), rob(nums, 1, n - 1)); 11 } 12 13 private int rob(int[] nums, int first, int last) { 14 int pre2 = 0, pre1 = 0; 15 for (int i = first; i <= last; i++) { 16 int cur = Math.max(pre1, pre2 + nums[i]); 17 pre2 = pre1; 18 pre1 = cur; 19 } 20 return pre1; 21 } 22 }
对比leetcode198:
1 public class LEET_198 { 2 public int rob(int[] nums) { 3 int pre2 = 0, pre1 = 0; 4 for (int i = 0; i < nums.length; i++) { 5 int cur = Math.max(pre2 + nums[i], pre1); 6 pre2 = pre1; 7 pre1 = cur; 8 } 9 return pre1; 10 } 11 }