您的位置:首页 > 产品设计 > UI/UE

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

2012-10-23 00:21 555 查看
M*N grids from top-left to bottom-right find all the paths.

public static int UniquePaths(int m, int n)
{
int ret = 0;
FindAllPaths(m, n, ref ret);
return ret;
}

public static void FindAllPaths(int m, int n, ref int numofpaths)
{
if (m == 1 && n == 1)
numofpaths++;
else
{
if (m > 1)
FindAllPaths(m - 1, n, ref numofpaths);
if (n > 1)
FindAllPaths(m, n - 1, ref numofpaths);
}
}


代码分析:

  递归做法。

public static int UniquePathsDP(int m, int n)
{
int[,] grid = new int[m, n];
grid[0,0] = 1;

for (int i = 1; i < m; i++)
grid[i, 0] = 1;
for (int i = 1; i < n; i++)
grid[0, i] = 1;

for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; j++)
{
grid[i, j] = grid[i - 1, j] + grid[i, j - 1];
}
}

return grid[m - 1, n - 1];
}


代码分析:

  DP做法,

  例如 M = 3, N = 4

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

  C(x, y) = x! / (y! * (x- y)!), 但是因为x!太大,很容易overflow,所以还是别用了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: