Unique Paths (method 1 recursion-Dynamic Programming Method 2 mathematical formula)

Source: Internet
Author: User

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 ");}
 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.