[leetcode]Unique Paths

本文探讨了一个机器人在限定网格中从左上角移动到右下角的不同路径数量问题。通过使用动态规划方法,定义了状态转移方程并给出了具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

题意:一个机器人在m X n的矩阵的左上角, 且每次只能向下或向右移动。问如果要移动最右下角有多少种方案?

解题思路:动态规划, 状态转移方程 dp[i][j] = dp[i + 1][j] + dp[i][j + 1], 数组最右边一列,及数组最下边一行初始化为1.

class Solution {
public:
    int uniquePaths(int m, int n) {
    	// Note: The Solution object is instantiated only once and is reused by each test case.
    	//动态规划
    	//一个机器人在m*n的格子左上角要到右下角去,只能向右或是向下移动,列出所有可走的路线数
    	//定义一个二维数组,用容器vector模拟,数组最下及最右一排为一,然后从右下方做叠加到左上方
    	vector<vector<int> > v;
    	vector<int> tmp(n, 1);
    	
    	for (int i = 0; i < m; i++){
    		v.push_back(tmp);
    	}
    	//处理非最右及最下的数据项
    	for (int i = m - 2; i >= 0; i--)
    	{
    		for (int j = n - 2; j >= 0; j--)
    		{
    		    //当前数据 等于 右面与下面数据之和
    			v[i][j] = v[i + 1][j] + v[i][j + 1];
    		}
    	}
        //返回总路径数
    	return v[0][0];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值