62. 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?
一個m x n 的格子圖中從左上角走到右下角共有多少條路徑?
動態規劃問題,可以用組合公式。一共要走n+m-2步,在其中選取n-1步爲向右走,剩下m-1步爲向下走。共有C(n-1,m+n-2)種路徑。
class Solution {
public:
int uniquePaths(int m, int n) {
int N = n + m - 2;
int k = m - 1;
double res = 1;
for (int i = 1; i <= k; i++)
res = res * (N - k + i) / i;
return (int)res;
}
};
100. Same Tree
Given two binary trees, write a function to check if they are equal or not.Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
判斷兩個二叉樹是否相同
採用遞歸的方法,判斷根的值,判斷左子樹,再判斷右子樹。
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL||q==NULL)
return (p==q);
if(p->val!=q->val)
return false;
if(!isSameTree(p->left,q->left))
return false;
if(!isSameTree(p->right,q->right))
return false;
return true;
}
};