Leetcode-climbing stairs

Source: Internet
Author: User

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?

//第一种解法class Solution {public:    int climbStairs(int n) {int ans[100] = {1,2};for (int i = 2; i < n; i++){ans[i] = ans[i-1] + ans[i-2];}return ans[n-1];    }};

Another solution is to use matrix + Rapid power and time complexity O (logn ). First, convert this problem into a matrix problem.

In this way, the problem is solved by using a quick power method.

class Matrix{public:Matrix();~Matrix();Matrix operator *(const Matrix &t);Matrix& operator=(const Matrix &t);int map[2][2];};Matrix::Matrix(){map[0][0] = 1;map[0][1] = 1;map[1][0] = 1;map[1][1] = 0;}Matrix Matrix::operator*(const Matrix &t){Matrix ans;      ans.map[0][0] = (map[0][0]*t.map[0][0]+map[0][1]*t.map[1][0]);    ans.map[0][1] = (map[0][0]*t.map[0][1]+map[0][1]*t.map[1][1]);    ans.map[1][0] = (map[1][0]*t.map[0][0]+map[1][1]*t.map[1][0]);    ans.map[1][1] = (map[1][0]*t.map[0][1]+map[1][1]*t.map[1][1]);    return ans;  }Matrix& Matrix::operator=(const Matrix &t){for(int i = 0; i <= 1; ++i)      {          for(int j = 0; j <= 1; ++j)          {              map[i][j] = t.map[i][j];          }      }      return *this;  }Matrix::~Matrix(){}class Solution {public:    int climbStairs(int n) {Matrix res,k;n = n + 1;while(n){if(n & 1) res = res * k;k = k * k;n >>= 1;}return res.map[1][1];    }};



Leetcode-climbing stairs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.