|
| 1 | +package io.github.juchanei.leetcodeJava; |
| 2 | + |
| 3 | +import org.junit.Assert; |
| 4 | +import org.junit.Test; |
| 5 | + |
| 6 | +public class UniquePaths { |
| 7 | + private int m; |
| 8 | + private int n; |
| 9 | + private int[][] cache; |
| 10 | + |
| 11 | + public int uniquePaths(int m, int n) { |
| 12 | + this.m = m; |
| 13 | + this.n = n; |
| 14 | + this.cache = new int[m][n]; |
| 15 | + |
| 16 | + return find(0, 0); |
| 17 | + } |
| 18 | + |
| 19 | + private int find(int i, int j) { |
| 20 | + if (i == m) return 0; |
| 21 | + if (j == n) return 0; |
| 22 | + if (i == m - 1 && j == n - 1) return 1; |
| 23 | + |
| 24 | + if (0 < cache[i][j]) return cache[i][j]; |
| 25 | + |
| 26 | + return cache[i][j] = find(i + 1, j) + find(i, j + 1); |
| 27 | + } |
| 28 | + |
| 29 | + public static class UnitTest { |
| 30 | + |
| 31 | + private UniquePaths up = new UniquePaths(); |
| 32 | + |
| 33 | + @Test |
| 34 | + public void example1() { |
| 35 | + int expected = 28; |
| 36 | + int actual = up.uniquePaths(3, 7); |
| 37 | + |
| 38 | + Assert.assertEquals(expected, actual); |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + public void example2() { |
| 43 | + int expected = 3; |
| 44 | + int actual = up.uniquePaths(3, 2); |
| 45 | + |
| 46 | + Assert.assertEquals(expected, actual); |
| 47 | + } |
| 48 | + |
| 49 | + @Test |
| 50 | + public void example3() { |
| 51 | + int expected = 28; |
| 52 | + int actual = up.uniquePaths(7, 3); |
| 53 | + |
| 54 | + Assert.assertEquals(expected, actual); |
| 55 | + } |
| 56 | + |
| 57 | + @Test |
| 58 | + public void example4() { |
| 59 | + int expected = 6; |
| 60 | + int actual = up.uniquePaths(3, 3); |
| 61 | + |
| 62 | + Assert.assertEquals(expected, actual); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments