leetcode #70 in cpp

原创 2016年05月31日 09:14:19

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?


Solution:

We use DP. see comments.

Code:

class Solution {
public:

    int climbStairs(int n) {
       vector<int> dp(n+1,0);//dp[i] = distinct ways from i to n
       if(n-1 >= 0) dp[n-1] = 1;//position with 1 step from destination. only 1 way to reach the destination
       if(n-2 >= 0) dp[n-2] = 2;//position with 2 steps from destination. only 2 way to reach the destination;
       for(int i = n-3; i >=0 ; i --){
           dp[i] = dp[i+2]+dp[i+1];//distinct ways from position i to n: 1. we take one step to i+1; 2. we take 2 steps to i+2
       }                            //thus distinct ways from position i to n is the sum of the ones at i+1 and i+2
       return dp[0];
       
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

leetcode #32 in cpp

Given a string containing just the characters '(' and ')', find the length of the longest valid (we...

leetcode #114 in cpp

Given a binary tree, flatten it to a linked list in-place. For example, Given 1 ...

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

leetcode #160 in cpp

Write a program to find the node at which the intersection of two singly linked lists begins. F...

Leetcode 285. Inorder Successor in BST (Medium) (cpp)

Leetcode 285. Inorder Successor in BST (Medium) (cpp)

leetcode #98 in cpp

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined...

leetcode #37 in cpp

The question is to solve a Sudoku. Solution: We scan through the Sudoku. Whenever we meet a '.', w...

leetcode #77 in cpp

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For exa...

leetcode #139 in cpp

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa...

leetcode #18 in cpp

The question is similar to 3sum. And how to solve it is thus very similar to the solution of 3sum.  ...

leetcode #44 in cpp

Solution:  We use DP to solve this problem.  Initialize bool dp[pattern length + 1][ s length + 1]...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)