Unique Paths (method 1 recursion-Dynamic Programming Method 2 mathematical formula)
A robot is located at the top-left corner ofMXNGrid (marked 'start' in the dimo-below ).
The robot can only move either down or right at any point in time. Therobot is trying to reach the bottom-right corner of the grid (marked 'finish 'in the dimo-below ).
How many possible unique paths are there?
Above is a 3x7 grid. How many possible unique paths are there?
Note: MAndNWillbe at most 100.
HideTags
Array Dynamic Programming
# Pragma once # include
Using namespace std; // Method 1: recursion, timeout int uniquePaths1 (int m, int n) {if (m = 2 | n = 2) return m + N-2; return uniquePaths1 (m-1, n) + uniquePaths1 (m, n-1);} // Method 2: mathematical formula for m + N-2 the sum of m-1 int uniquePaths2 (int m, int n) {long result = 1; int reduce = m-1; for (int I = m-1; I> = 1; I --) {result * = (n-1 + I ); while (reduce> 0 & result % reduce = 0) {result = result/reduce; reduce -- ;}// after the while clause is used in the inner loop, because the final result must be divisible, you do not need to add the following/* while (reduce> 0) {result = result/reduce;} */return result;} void main () {cout <uniquePaths2 (36, 7) <endl; cout <uniquePaths1 (36, 7) <endl; system ("pause ");}