在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Follow up for "Unique Paths": [ Note: m and n will be at most 100. 1 public static int UniquePathsIIDP(List<List<int>> obstacleGrid) 2 { 3 int m = obstacleGrid.Count; 4 int n = obstacleGrid[0].Count; 5 int[,] grid = new int[m, n]; 6 7 // if the start point is a obstacle, return 0 8 if (obstacleGrid[0][0] == 1) 9 return 0; 10 grid[0, 0] = 1; 11 12 for (int i = 1; i < m; i++) 13 { 14 if (obstacleGrid[i][0] == 0 && grid[i - 1, 0] != 0) 15 grid[i, 0] = 1; 16 else 17 grid[i, 0] = 0; 18 } 19 20 for (int i = 1; i < n; i++) 21 { 22 if (obstacleGrid[0][i] == 0 && grid[0, i - 1] != 0) 23 grid[0, i] = 1; 24 else 25 grid[0, i] = 0; 26 } 27 28 for (int i = 1; i < m; i++) 29 { 30 for (int j = 1; j < n; j++) 31 { 32 if (obstacleGrid[i][j] == 1) 33 grid[i, j] = 0; 34 else 35 grid[i, j] = grid[i - 1, j] + grid[i, j - 1]; 36 } 37 } 38 39 return grid[m - 1, n - 1]; 40 } 代码分析: 这题用DP,超容易。 |
请发表评论