Unique paths <leetcode>
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?
思路:首先想到的是广度优先搜索(分支限界),方法一就是,但是超时,方法二是动态规划,accepted
1 struct node 2 { 3 int x; 4 int y; 5 }; 6 class Solution { 7 public: 8 int total_path; 9 int uniquePaths(int m, int n) { 10 total_path=0; 11 list<node> ls; 12 node orign; 13 orign.x=1; 14 orign.y=1; 15 ls.push_back(orign); 16 while(ls.size()!=0) 17 { 18 node temp=ls.front(); 19 ls.pop_front(); 20 if(temp.x+1<=n) 21 { 22 node p; 23 p.x=temp.x+1; 24 p.y=temp.y; 25 ls.push_back(p); 26 if(temp.x+1==n&&temp.y==m) 27 { 28 total_path++; 29 } 30 } 31 if(temp.y+1<=m) 32 { 33 node p; 34 p.x=temp.x; 35 p.y=temp.y+1; 36 ls.push_back(p); 37 if(temp.x==n&&temp.y+1==m) 38 { 39 total_path++; 40 } 41 } 42 } 43 return total_path; 44 } 45 };
方法二:动态规划
1 class Solution { 2 public: 3 int uniquePaths(int m, int n) { 4 int f[m][n]; 5 memset(f,0,sizeof(int)*m*n); 6 7 for(int i=0;i<m;i++) 8 { 9 f[i][0]=1; 10 } 11 for(int i=0;i<n;i++) 12 { 13 f[0][i]=1; 14 } 15 16 for(int i=1;i<m;i++) 17 { 18 for(int j=1;j<n;j++) 19 { 20 f[i][j]=f[i-1][j]+f[i][j-1]; 21 } 22 } 23 return f[m-1][n-1]; 24 } 25 };