LeetCode 62. Unique Paths
来源:互联网 发布:win10ie无法下载软件 编辑:程序博客网 时间:2024/06/06 12:33
问题
求组合数C(n, m);
解法
使用递推公式 C(n, m) = C(n-1, m-1) + C(n-1, m);
理解: 从n个元素中取出m个元素, 考虑存在一个特殊元素,第一类取法不包括特殊元素则从其他元素中拿m个,有C(n-1, m) 种方案, 第二类取法包括特殊元素则从其他元素中拿m-1个有C(n-1, m-1)种方案。
边界条件: 规定C(n, 0) = 1;
class Solution {public: int C(int n, int m) { int now = 0; dp[0][0] = dp[1][0] = 1;// C(n, 0) = 1; dp[0][1] = 1; for (int i= 2; i<=n; ++i) { for (int j= 1; j<=m; ++j) dp[!now][j] = dp[now][j-1] + dp[now][j]; now = !now; } return dp[now][m]; } int uniquePaths(int m, int n) { return C(m+n-2, min(m-1, n-1)); }private: int dp[2][102];};
解法二 动态规划
class Solution {public: int uniquePaths(int m, int n) { memset(dp, 0, sizeof(dp)); int read = 0; dp[read][n] = 1; for (int i=m; i>0; --i) { int write = !read; for (int j = n; j > 0; --j) { dp[write][j] = dp[read][j] + dp[write][j+1]; } read = !read; } return dp[read][1]; }private: int dp[2][102];};
0 0
- [LeetCode]62.Unique Paths
- LeetCode --- 62. Unique Paths
- LeetCode 62.Unique Paths
- [Leetcode] 62. Unique Paths
- [leetcode] 62.Unique Paths
- [leetcode] 62.Unique Paths
- leetcode 62. Unique Paths
- Leetcode 62. Unique Paths
- [leetcode] 62. Unique Paths
- 62. Unique Paths LeetCode
- [LeetCode]62. Unique Paths
- 【LeetCOde】62. Unique Paths
- [LeetCode]62. Unique Paths
- leetcode 62. Unique Paths
- LeetCode 62. Unique Paths
- LeetCode *** 62. Unique Paths
- leetcode 62. Unique Paths
- Leetcode:62. Unique Paths
- WebView的用法
- [leetcode]【数组】33. Search in Rotated Sorted Array
- ORACLE 10.2.0.1 ,10gr2 rac 搭建步骤详细
- PaletteDemoMaterial Design使用动态颜色
- 如何用正则表达式匹配包括换行符的任意字符?
- LeetCode 62. Unique Paths
- 2016"百度之星" - 初赛(Astar Round2A)解题报告
- Clime Cross GFW
- IOCP例子二
- 菜鸟的第一篇C博:希望成长
- ORA-01157 错误解决,原因DBWR锁定产生
- HDU 2571
- 如何解决Tomcat启动时重复出现Socket accept failed错误
- Android打造ListView万能适配器