54. Search a 2D Matrix && Climbing Stairs (Easy)

 

 

 

 

 

Search a 2D Matrix

  

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

思路: 从右上方开始,若小于 target, 则往下走;若大于 target, 对改行二分查找;若等 target, 返回 true.

bool binarySearch(vector<int> &A, int target) {
    int l = 0, h = A.size()-2;
    while(l <= h) {
        int mid = (l+h) >> 1;
        if(A[mid] > target) h = mid-1;
        else if(A[mid] < target) l = mid+1;
        else return true;
    }
    return false;
}
class Solution {
public:
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        if(!matrix.size() || !matrix[0].size()) return false;
        int row = matrix.size(), col = matrix[0].size();
        for(int r = 0; r < row; ++r) {
            if(matrix[r][col-1] == target) return true;
            if(matrix[r][col-1] > target) return binarySearch(matrix[r], target);
        }
        return false;
    }
};

Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

思路:  斐波那契。此处用动归。 还可以使用矩阵二分乘。(剑指offer: 题9)

// Fibonacci
class Solution {
public:
    int climbStairs(int n) {
        vector<int> f(n+1, 0);
        f[0] = f[1] = 1;
        for(int i = 2; i <= n; ++i) f[i] = f[i-1] + f[i-2];
        return f[n];
    }
};
原文地址:https://www.cnblogs.com/liyangguang1988/p/3954305.html