From dd7003d53c61ef79deeb7f4a58ed91a68556c25b Mon Sep 17 00:00:00 2001 From: potrue <126231160+potrue@users.noreply.github.com> Date: Mon, 4 Aug 2025 14:46:22 +0900 Subject: [PATCH] 63. Unique Paths II MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 問題文: https://leetcode.com/problems/unique-paths-ii/description/ --- 63/63.md | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 63/63.md diff --git a/63/63.md b/63/63.md new file mode 100644 index 0000000..d7f7b65 --- /dev/null +++ b/63/63.md @@ -0,0 +1,94 @@ +## 何も見ずに解いてみる + +```cpp +class Solution { +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + vector> num_paths(obstacleGrid.size(), vector(obstacleGrid[0].size(), 0)); + if (obstacleGrid[0][0] == 1) { + return 0; + } + num_paths[0][0] = 1; + for (int i = 0; i < obstacleGrid.size(); i++) { + for (int j = 0; j < obstacleGrid[0].size(); j++) { + if (obstacleGrid[i][j] == 1) { + continue; + } + if (i != 0) { + num_paths[i][j] += num_paths[i-1][j]; + } + if (j != 0) { + num_paths[i][j] += num_paths[i][j-1]; + } + } + } + return num_paths.back().back(); + } +}; +``` + +## 他の人の解答を見てみる + +https://github.com/ryosuketc/leetcode_arai60/pull/47/files +https://github.com/tokuhirat/LeetCode/pull/34/files +https://github.com/irohafternoon/LeetCode/pull/37/files +https://github.com/philip82148/leetcode-swejp/pull/10/files + +最初の行と列を別の枠で初期化しているやり方をしているコードも結構あるが、個人的には`i != 0`や`i > 0`で条件分岐するやり方のほうが見やすいと感じた。 + +列のサイズの配列で行うバージョン + +```cpp +class Solution { +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + int num_rows = obstacleGrid.size(); + int num_columns = obstacleGrid[0].size(); + vector num_paths_current_row(num_columns, 0); + num_paths_current_row[0] = 1; + for (int i = 0; i < num_rows; i++) { + for (int j = 0; j < num_columns; j++) { + if (obstacleGrid[i][j] == 1) { + num_paths_current_row[j] = 0; + continue; + } + if (j > 0) { + num_paths_current_row[j] += num_paths_current_row[j - 1]; + } + } + } + return num_paths_current_row.back(); + } +}; +``` + +## 最終コード + +```cpp +class Solution { +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + int num_rows = obstacleGrid.size(); + int num_columns = obstacleGrid[0].size(); + vector> num_paths(num_rows, vector(num_columns, 0)); + if (obstacleGrid[0][0] == 1) { + return 0; + } + num_paths[0][0] = 1; + for (int i = 0; i < num_rows; i++) { + for (int j = 0; j < num_columns; j++) { + if (obstacleGrid[i][j] == 1) { + continue; + } + if (i != 0) { + num_paths[i][j] += num_paths[i-1][j]; + } + if (j != 0) { + num_paths[i][j] += num_paths[i][j-1]; + } + } + } + return num_paths.back().back(); + } +}; +```