From 164a5ff20ae0379be5090e7f2b81b0eadddbe6ab Mon Sep 17 00:00:00 2001 From: gringrape Date: Sat, 31 Dec 2022 14:44:01 +0900 Subject: [PATCH] =?UTF-8?q?UniquePaths=20=EB=AC=B8=EC=A0=9C=20=ED=92=80?= =?UTF-8?q?=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: https://leetcode.com/problems/unique-paths/ --- 20221231/unique-paths/README.md | 18 ++++++++++ 20221231/unique-paths/test_unique_paths.py | 42 ++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 20221231/unique-paths/README.md create mode 100644 20221231/unique-paths/test_unique_paths.py diff --git a/20221231/unique-paths/README.md b/20221231/unique-paths/README.md new file mode 100644 index 0000000..4dd0f2f --- /dev/null +++ b/20221231/unique-paths/README.md @@ -0,0 +1,18 @@ +# Unique Paths +## 문제 설명 +- `m x n` 격자가 주어진다. +- 로봇은 격자의 좌상단 맨끝에서 출발해서 우하단 맨끝으로 이동한다. +- 로봇은 한 번 이동할때, 우측으로 한칸 또는 아래로 한칸 이동한다. +- 이때, 로봇이 지나는 경로 중 unique 한 것들의 개수를 구하여라. + +## 풀이 계획 +- 위치별 경로 개수간의 관계가 존재함. +- 관계를 점화식으로 표현가능. + +``` +pathCount(row, column) = pathCount(row + 1, column) + pathCount(row, column + 1) +``` + +## 풀이 계획 +- 재귀 프로시저를 구성할 수 있지만, 재귀 경로가 겹치는 재귀적 프로세스가 생성되어 효율성이 떨어진다. +- 동적 프로그래밍 방법론을 활용 가능하다. diff --git a/20221231/unique-paths/test_unique_paths.py b/20221231/unique-paths/test_unique_paths.py new file mode 100644 index 0000000..c3f6004 --- /dev/null +++ b/20221231/unique-paths/test_unique_paths.py @@ -0,0 +1,42 @@ +def uniquePaths_simple_recursion(m, n): + def countPaths(r, c): + if r == m - 1 and c == n - 1: + return 1 + + if r < 0 or r >= m or c < 0 or c >= n: + return 0 + + return countPaths(r + 1, c) + countPaths(r, c + 1) + + return countPaths(0, 0) + + +def uniquePaths_memoization(m, n): + counts = dict() + + def countPaths(r, c): + if r == m - 1 and c == n - 1: + return 1 + + if r < 0 or r >= m or c < 0 or c >= n: + return 0 + + position = f'{r}-{c}' + if position not in counts: + counts[f'{r}-{c}'] = countPaths(r + 1, c) + countPaths(r, c + 1) + + return counts[position] + + return countPaths(0, 0) + + +solutions = [ + uniquePaths_simple_recursion, + uniquePaths_memoization, +] + + +def test_unique_paths(): + for uniquePaths in solutions: + assert uniquePaths(m=3, n=7) == 28 + assert uniquePaths(m=3, n=2) == 3