diff --git a/62/step1.cpp b/62/step1.cpp new file mode 100644 index 0000000..6850bf7 --- /dev/null +++ b/62/step1.cpp @@ -0,0 +1,28 @@ +// Time: 07:01 + +// Time Space: O(m * n) +// Memory Space: O(m * n) + +/* +上と左の経路数をそのまま合計していき、それを繰り返すというのを思いつけたのでそのまま実装 +変数名が若干分かりづらいので、grid、というコンテキストに適した名前にするとよさそう +*/ + +class Solution { +public: + int uniquePaths(int m, int n) { + vector> grid(m, vector(n, 0)); + grid[0][0] = 1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (i > 0) { + grid[i][j] += grid[i-1][j]; + } + if (j > 0) { + grid[i][j] += grid[i][j-1]; + } + } + } + return grid[m-1][n-1]; + } +}; diff --git a/62/step2_1.cpp b/62/step2_1.cpp new file mode 100644 index 0000000..e6dde50 --- /dev/null +++ b/62/step2_1.cpp @@ -0,0 +1,22 @@ +/* +変数名を微修正 +*/ +class Solution { +public: + int uniquePaths(int m, int n) { + vector> grid(m, vector(n, 0)); + grid[0][0]=1; + + for (int y = 0; y < m; ++y) { + for (int x = 0; x < n; ++x) { + if (x > 0) { + grid[y][x] += grid[y][x - 1]; + } + if(y > 0) { + grid[y][x] += grid[y-1][x]; + } + } + } + return grid[m-1][n-1]; + } +}; diff --git a/62/step2_2.cpp b/62/step2_2.cpp new file mode 100644 index 0000000..47977f0 --- /dev/null +++ b/62/step2_2.cpp @@ -0,0 +1,24 @@ +/* +単一の配列で実行するのを試す +*/ +class Solution { +public: + int uniquePaths(int m, int n) { + vector step_counter(n, 0); + step_counter[0] = 1; + + for (int y = 0; y < m; ++y) { + for(int x = 1; x < n; ++x) { + int step = 0; + if (y > 0) { + step += step_counter[x]; + } + if (x > 0) { + step += step_counter[x - 1]; + } + step_counter[x] = step; + } + } + return step_counter.back(); + } +}; diff --git a/62/step3.cpp b/62/step3.cpp new file mode 100644 index 0000000..6451dd1 --- /dev/null +++ b/62/step3.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int uniquePaths(int m, int n) { + vector> step_count(m, vector(n, 0)); + step_count[0][0] = 1; + for (int row = 0; row < m; ++row) { + for (int col = 0; col < n; ++col) { + if (col == 0 && row == 0) { + continue; + } + if (row > 0) { + step_count[row][col] += step_count[row - 1][col]; + } + if (col > 0) { + step_count[row][col] += step_count[row][col - 1]; + } + } + } + return step_count[m - 1][n - 1]; + } +};