File tree Expand file tree Collapse file tree 3 files changed +52
-0
lines changed Expand file tree Collapse file tree 3 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 81
81
160. 相交链表
82
82
169. 多数元素
83
83
188. 买卖股票的最佳时机 IV
84
+ 198. 打家劫舍
84
85
199. 二叉树的右视图
85
86
200. 岛屿数量
86
87
203. 移除链表元素
Original file line number Diff line number Diff line change 74
74
139. 单词拆分
75
75
152. 乘积最大子数组
76
76
188. 买卖股票的最佳时机 IV
77
+ 198. 打家劫舍
77
78
279. 完全平方数
78
79
300. 最长上升子序列
79
80
309. 最佳买卖股票时机含冷冻期
Original file line number Diff line number Diff line change
1
+ // 198. 打家劫舍
2
+
3
+
4
+ /*
5
+ 动态规划:
6
+ 1、定义dp数组:dp[i] 表示在第i号房屋时能偷窃到的最高金额
7
+ 2、初始化:
8
+ 1)dp[0]=0 表示没有偷窃时金额为0,dp[1]=nums[0] 表示第1号房屋时偷窃最高金额为nums[0]
9
+ 2)因为状态转移方程由前两项推出,所以要先初始化前两项
10
+ 3、状态转移方程:
11
+ 1)如果偷窃第i号房屋,那么i-1号房屋不能偷窃,则最高金额为 dp[i-2] + nums[i - 1]
12
+ 2)如果不偷窃第i号房屋,那么最高金额同i-1号房屋一样,即 dp[i - 1]
13
+ 3)在 偷窃 和 不偷窃 选择最高金额,即 dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1]);
14
+ 4、遍历dp数组填表:从索引2开始遍历,根据状态转移方程填表
15
+ 5、返回结果:最后一个状态就是结果
16
+ */
17
+ class Solution {
18
+ public int rob (int [] nums ) {
19
+ int n = nums .length ;
20
+ if (n == 0 ) {
21
+ return 0 ;
22
+ }
23
+ int [] dp = new int [n + 1 ];
24
+ dp [1 ] = nums [0 ];
25
+ for (int i = 2 ; i <= n ; i ++) {
26
+ dp [i ] = Math .max (dp [i - 1 ], dp [i - 2 ] + nums [i - 1 ]);
27
+ }
28
+ return dp [n ];
29
+ }
30
+ }
31
+
32
+
33
+ /*
34
+ 状态压缩:由于dp数组只用到前两项,所以用两个变量替代即可,表示前两个房屋能偷窃到的最高金额,动态更新两个变量的值
35
+ */
36
+ class Solution {
37
+ public int rob (int [] nums ) {
38
+ int n = nums .length ;
39
+ if (n == 0 ) {
40
+ return 0 ;
41
+ }
42
+ int pre = 0 , cur = nums [0 ];
43
+ for (int i = 2 ; i <= n ; i ++) {
44
+ int temp = cur ;
45
+ cur = Math .max (cur , pre + nums [i - 1 ]);
46
+ pre = temp ;
47
+ }
48
+ return cur ;
49
+ }
50
+ }
You can’t perform that action at this time.
0 commit comments