soulmachine/leetcode

An optimized sol for 10.2.4

billlipeng opened this issue · 1 comments

2ms with the following sol.
Optimized the combination part.

class Solution {
public:
    int uniquePaths(int m, int n) {
        if(!m || !n) return 0;

        long long a = 1,b = 1;

        // find the max
        int min = m < n ? m : n;
        int max = m > n ? m : n;

        // find (m+n-2)!/max{(m-1)!,(n-1)!}
        for(int i=max;i<=m+n-2;++i)  a *= i;
        // min{(m-1)!,(n-1)!}
        for(int i=1;i<=min-1;++i)    b *= i;

        return a/b;
    }
};

Sorry guys. I didn't read the original code carefully. The one I posted has the same machine code with the original one, with less lines of c++ code.