Conversation
| // 数学を使わずにゴリゴリにやるとしたら、全ての経路を通ってから、その経路を set で保存して、その set の長さを返せばいい。 | ||
| // 全ての経路をしらみつぶしに通るには、O(2^(m+n-2))通りを処理する必要がある。 |
There was a problem hiding this comment.
本題から逸れますが,「→」と「↓」を自由に用いて
(経路を数えるならしらみ潰しにしても最終的な答えと同じ
There was a problem hiding this comment.
何も考えずに全部の位置で「→」と「↓」にいく選択肢があり、各マスで2通りの進み方があるから 2^(m+n-2) かなと思って書きましたが、特にこの方法でも経路の重複がなさそうなので、確かに最終的な答えと同じになると思います。
| if (num2 > num1) { | ||
| throw Exception("num1 should be larger than num2."); | ||
| } |
There was a problem hiding this comment.
せっかくなら,非正整数も弾いてあげると良いかもしれません(本体関数の方で弾いているので問題はないですが再利用することを考えて).
| if (m < 0 || n < 0) { | ||
| throw Exception("Both of inputs should be larger than 0."); | ||
| } |
There was a problem hiding this comment.
nit: エラーメッセージに整合的にするにはif (m <= 0 || n <= 0)ですね.
| if (num2 > num1) { | ||
| throw Exception("num1 should be larger than num2."); | ||
| } | ||
|
|
| uniquePathsCounts[row][col] = 1; | ||
| return uniquePathsCounts[row][col]!; | ||
| } | ||
|
|
There was a problem hiding this comment.
私なら3つのif分岐を「再帰呼び出し不要のパターン」として一つの塊と見て,ここの空行は入れないです.好みの問題でしょう.
|
|
||
| // 一次元配列の方法も書いておく | ||
| class Solution { | ||
| int uniquePaths(int m, int n) { |
| throw Exception("Both of inputs should be larger than 0."); | ||
| } | ||
|
|
||
| var uniquePathsCounts = List.generate(m, (_) => List<int?>.filled(n, null)); |
There was a problem hiding this comment.
私がちょっと調べた範囲では、dartの標準では関数のメモ化をサポートする機能は無く、自前でキャッシュを管理しないといけなさそうですね。
サードパーティのライブラリはありそうでしたが…。
https://pub.dev/packages/cached
| return uniquePathsCounts[row][col]!; | ||
| } | ||
|
|
||
| uniquePathsCounts[row][col] = helper(row - 1, col) + helper(row, col - 1); |
There was a problem hiding this comment.
ヘルパー関数の名前にも親の uniquePaths が入ったほうが、前の結果を積み上げている感じがして好みです。実質的に helper ≒ uniquePaths なんですが、それが名前に入っていたほうが頭の中の変換がひとつ省略できるというか。
| uniquePathsCounts[row][col] = helper(row - 1, col) + helper(row, col - 1); | |
| uniquePathsCounts[row][col] = uniquePathsHelper(row - 1, col) + uniquePathsHelper(row, col - 1); |
解いた問題:https://leetcode.com/problems/unique-paths/description/
次に解く問題:https://leetcode.com/problems/unique-paths-ii/description/