Niuke Net Brushing Questions-Finding Path

Problem Description

A robot is in the upper left corner (starting point) of an m×n map.
The robot moves down or to the right every time. The robot has to reach the lower right corner (end point) of the map.
How many different paths can be taken from the start to the end?

Input description:
input m, n

Output description:
the number of output paths

Example

Example 1

Enter
2,1

Output
2

Solutions

analysis

  1. The robot can only go to the right and down, so the rule can be summarized as follows (you can also verify it yourself):
    Number of paths = number of paths on the left + number of paths on the upper side

method

  1. Solve by loop or recursion

Code

public class Solution {
    
    
    public int uniquePaths (int m, int n) {
    
    
        // write code here
        int[][] path = new int[m][n];
        for (int i = 0; i < n; i++) {
    
    
            path[0][i] = 1;
        }

        for (int i = 0; i < m; i++) {
    
    
            path[i][0] = 1;
        }

        // 计算路径
        for (int i = 1; i < m; i++) {
    
    
            for (int j = 1; j < n; j++) {
    
    
                // 机器人只能向右和向下走,所以可以总结出规律如下(也可自己验证一下)
                // 路径计算的规律:路径数=左侧的路径数+上侧的路径数
                path[i][j] = path[i][j - 1] + path[i - 1][j];
            }
        }

        return path[m - 1][n - 1];
    }
}

If you want to test, you can go directly to the link of Niuke.com to do the test

Find the path-niuke.com

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/112972692