Unique Paths

来源:互联网 发布:淘宝网白的确良布商家 编辑:程序博客网 时间:2024/04/30 03:22

Unique Paths

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.

方法一:不同路径个数路径C(m+n-2,m);

class Solution {public:    int gcd(int a,int b){        if (a>b)            swap(a,b);        while (b!=0){            int temp = a;            a = b;            b = temp%b;        }        return a;    }    int uniquePaths(int m, int n) {        if ( m==1 && n==1 ) return 1;        int sum = 1;        int sum1 = 1;                int index = m-1;        if (m>n) index = n-1;        int temp = n+m-2;        while (index){            if (sum >10000000){                int a = gcd(sum,sum1);                sum /=a;                sum1/=a;            }            sum *=temp--;            sum1 *=index--;        }        return sum/sum1;    }};


0 0
原创粉丝点击