机器人到达终点有几条路径?

0

问题:

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?

网上的答案基本都是使用动态规划的方式来实现统计,不考虑时间复杂度的话其实有多重方案。

1.分治法

 public static int treatment(int x,int y){
    if( x==1 || y==1 ) return 1;
    return treatment(x-1, y)+treatment(x, y-1);
  }

2.回溯法

 public static int test3(int x, int y) {
    // 回溯 机器人走迷宫
    int left = x - 1, right = y - 1;
    int count = huisu(0, 0, left, right);
    return count;
  }

  public static int huisu(int x, int y, int left, int right) {
    int count = 0;

    if (x == left && y == left) {
      return ++count;
    }

    if (x + 1 <= left) {
      x++;
      count += huisu(x, y, left, right);
      x--; // 回溯条件
    }


    if (y + 1 <= right) {
      y++;
      count += huisu(x, y, left, right);
    }

    return count;
  }

3.动态规划

private static int dp(int m, int n) {
    int[][] dp = new int[m][n];
    for (int i = 0; i < m; i++) {
      dp[i][0] = 1;
    }
    for (int j = 0; j < n; j++) {
      dp[0][j] = 1;
    }
    for (int i = 1; i < m; i++) {
      for (int j = 1; j < n; j++) {
        dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
      }
    }
    return dp[m - 1][n - 1];

  }

你可能感兴趣的

Nora · 6月20日

我竟然刷到了美图的面试题

回复

0

这只是最基本的算法题,只要会回溯万能大法,这种问题都可以迎刃而解

花溪的小石头 作者 · 6月28日
载入中...