File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ *** 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。给定一个代表每个房屋存放金额的非负整数数组,计算你不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。***
2
+
3
+ ```
4
+ class Solution:
5
+ def rob(self, nums: List[int]) -> int:
6
+ n = len(nums)
7
+ if n<3:
8
+ return max(nums)
9
+
10
+ dp = [0]*n
11
+ dp[0] = nums[0]
12
+ dp[1] = max(nums[:2])
13
+
14
+ for i in range(2, n):
15
+ dp[i] = max(dp[i-2]+nums[i], dp[i-1])
16
+ return dp[-1]
17
+ ```
Original file line number Diff line number Diff line change
1
+ *** 给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。此外,你可以假设该网格的四条边均被水包围。***
2
+
3
+ ```
4
+ 输入:grid = [
5
+ ["1","1","0","0","0"],
6
+ ["1","1","0","0","0"],
7
+ ["0","0","1","0","0"],
8
+ ["0","0","0","1","1"]
9
+ ]
10
+ 输出:3
11
+ ```
12
+
13
+ ```
14
+ class Solution:
15
+ def numIslands(self, grid: List[List[str]]) -> int:
16
+ count = 0
17
+ #构造递归
18
+ def dfs(i, j):
19
+ #递归终止条件
20
+ if not 0<=i<len(grid) or not 0<=j<len(grid[0]) or grid[i][j] == '0':
21
+ return
22
+ grid[i][j] = '0'
23
+ dfs(i+1,j)
24
+ dfs(i-1,j)
25
+ dfs(i,j+1)
26
+ dfs(i,j-1)
27
+
28
+ for i in range(len(grid)):
29
+ for j in range(len(grid[0])):
30
+ if grid[i][j] == '1':
31
+ #调用递归
32
+ dfs(i,j)
33
+ count += 1
34
+ #返回要优化的目标
35
+ return count
36
+ ```
You can’t perform that action at this time.
0 commit comments