LeetCode Online Judge 题目C# 练习 - Unique Paths

M*N grids from top-left to bottom-right find all the paths.

 1         public static int UniquePaths(int m, int n)
 2         {
 3             int ret = 0;
 4             FindAllPaths(m, n, ref ret);
 5             return ret;
 6         }
 7 
 8         public static void FindAllPaths(int m, int n, ref int numofpaths)
 9         {
10             if (m == 1 && n == 1)
11                 numofpaths++;
12             else
13             {
14                 if (m > 1)
15                     FindAllPaths(m - 1, n, ref numofpaths);
16                 if (n > 1)
17                     FindAllPaths(m, n - 1, ref numofpaths);
18             }
19         }

代码分析:

  递归做法。

 1         public static int UniquePathsDP(int m, int n)
 2         {
 3             int[,] grid = new int[m, n];
 4             grid[0,0] = 1;
 5 
 6             for (int i = 1; i < m; i++)
 7                 grid[i, 0] = 1;
 8             for (int i = 1; i < n; i++)
 9                 grid[0, i] = 1;
10 
11             for (int i = 1; i < m; i++)
12             {
13                 for (int j = 1; j < n; j++)
14                 {
15                     grid[i, j] = grid[i - 1, j] + grid[i, j - 1];
16                 }
17             }
18 
19             return grid[m - 1, n - 1];
20         }

代码分析:

  DP做法,

  例如 M = 3, N = 4

1 1 1 1
1 2 3 4
1 3 6 10

 

  其实应该还有一种方法,C(m - 1 + n - 1, m - 1),就是在5步里面,找出2步是往下走的。

  C(x, y) = x! / (y! * (x- y)!), 但是因为x!太大,很容易overflow,所以还是别用了。

posted @ 2012-10-23 00:21  ETCOW  阅读(263)  评论(0编辑  收藏  举报