首页 > 代码库 > LeetCode_61uniquePaths [Unique Paths]
LeetCode_61uniquePaths [Unique Paths]
#pragma warning(disable:4996) #include <cstdio> #include <Windows.h> #include <tchar.h> /* submit time : 3 1. Time Limit Exceeded 23, 12 request : A robot is located at the top-left corner of a m x n grid (marked ‘Start‘ in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish‘ in the diagram below). How many possible unique paths are there? Above is a 3 x 7 grid. How many possible unique paths are there? Note: m and n will be at most 100. */ /* * 二逼解法 void uniquePathsRecursively(int& count, int row, int column, int rows, int columns) { if (row == rows && column == columns) { ++count; return; } if (row < rows) uniquePathsRecursively(count, row + 1, column, rows, columns); if (column < columns) uniquePathsRecursively(count, row, column + 1, rows, columns); } int uniquePaths(int m, int n) { if (m == 0 || n == 0) return 0; if (m == 1 || n == 1) return 1; int count = 0; uniquePathsRecursively(count, 1, 1, m, n); return count; } */ /* 一共要走m-1 + n-1步, 其中向下m-1步,向右n-1步, 所以结果就是C m-1 m+n-2 */ long long factorial(int k) { if (k == 0) return 1; long long fact = 1; for (int i = 1; i <= k; ++i) fact *= i; return fact; } int c(int bottom, int top) { int diff = bottom - top; if (top > diff) return c(bottom, diff); double res = 1.0; int i = bottom, j = top; while (j) { res *= (double)i / j; --i; --j; } int result = (int)(res + 0.5); return result; } int uniquePaths(int m, int n) { if (m == 0 || n == 0) return 0; if (m == 1 || n == 1) return 1; return c(m + n - 2, m - 1); } //===================Test================== void Test1() { int m = 23, n = 12; printf("%d\n", uniquePaths(m, n)); } void Test2() { int m = 3, n = 7; printf("%d\n", uniquePaths(m, n)); } int _tmain(int argc, _TCHAR* argv[]) { Test1(); Test2(); system("pause"); return 0; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。