|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | + |
| 4 | +public class Solution |
| 5 | +{ |
| 6 | + #region Approach 1 (Dynamic Programming Using Matrix) |
| 7 | + public static int UniquePaths_UsingMatrix(int m, int n) |
| 8 | + { |
| 9 | + if (m < 1 || m > 100 || n < 1 || n > 100) |
| 10 | + { |
| 11 | + return 0; |
| 12 | + } |
| 13 | + |
| 14 | + int[,] matrixPaths = new int[m + 1, n + 1]; |
| 15 | + matrixPaths[m - 1, n - 1] = 1; |
| 16 | + |
| 17 | + for (int row = m - 1; row >= 0; row--) |
| 18 | + { |
| 19 | + for (int col = n - 1; col >= 0; col--) |
| 20 | + { |
| 21 | + matrixPaths[row, col] = matrixPaths[row + 1, col] + matrixPaths[row, col + 1]; |
| 22 | + |
| 23 | + if (matrixPaths[row, col] == 0) |
| 24 | + { |
| 25 | + matrixPaths[row, col] = 1; |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + return matrixPaths[0, 0]; |
| 31 | + } |
| 32 | + #endregion |
| 33 | + |
| 34 | + #region Approach 2 (Dynamic Programming Using Array) |
| 35 | + public static int UniquePaths_UsingArray(int m, int n) |
| 36 | + { |
| 37 | + if (m < 1 || m > 100 || n < 1 || n > 100) |
| 38 | + { |
| 39 | + return 0; |
| 40 | + } |
| 41 | + |
| 42 | + int[] row = Enumerable.Repeat(1, n).ToArray(); |
| 43 | + |
| 44 | + foreach (int i in Enumerable.Range(0, m - 1)) |
| 45 | + { |
| 46 | + var newRow = Enumerable.Repeat(1, n).ToArray(); |
| 47 | + |
| 48 | + for (int j = n - 2; j >= 0; j--) |
| 49 | + { |
| 50 | + newRow[j] = newRow[j + 1] + row[j]; |
| 51 | + } |
| 52 | + |
| 53 | + row = newRow; |
| 54 | + } |
| 55 | + |
| 56 | + return row[0]; |
| 57 | + } |
| 58 | + #endregion |
| 59 | + |
| 60 | + public static void Main(string[] args) |
| 61 | + { |
| 62 | + Console.WriteLine(UniquePaths_UsingArray(1, 1)); |
| 63 | + |
| 64 | + Console.ReadKey(); |
| 65 | + } |
| 66 | +} |
| 67 | + |
0 commit comments