#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; }
LeetCode_61uniquePaths [Unique Paths],布布扣,bubuko.com
LeetCode_61uniquePaths [Unique Paths]
原文地址:http://my.oschina.net/ITHaozi/blog/294746