• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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?

推荐方法:DP矩阵做法其实还可以节省一维:2D矩阵变成一维数组DP:

 1 public int uniquePaths(int m, int n) {
 2     if(m<=0 || n<=0)
 3         return 0;
 4     int[] res = new int[n];
 5     res[0] = 1;
 6     for(int i=0;i<m;i++)
 7     {
 8         for(int j=1;j<n;j++)
 9         {
10            res[j] += res[j-1];
11         }
12     }
13     return res[n-1];
14 }

一维DP方法2:

 1 public class Solution {
 2     public int uniquePaths(int m, int n) {
 3         if (m == 0 || n == 0) return 0;
 4         int[] res = new int[n];
 5         for (int k=0; k<n; k++) {
 6             res[k] = 1;
 7         }
 8         for (int i=1; i<m; i++) {
 9             for (int j=1; j<n; j++) {
10                 res[j] = res[j-1] + res[j];
11             }
12         }
13         return res[n-1];
14     }
15 }

 

posted @ 2014-05-14 06:01  neverlandly  阅读(369)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3