• Leetcode 题目整理 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?

    Note: Given n will be a positive integer.

    对这种题目开始没有什么思路,借鉴博客http://blog.csdn.net/kenden23/article/details/17377869 给出的递归的思想。每次有两种选择,两种选择之后又是各有两种选择,如此循环,正好是递归求解的问题。

    int Solution::climbStairs(int n) {
    	//直接进行递归
    	if (n == 1) return 1;
    	if (n == 2) return 2;
    	return climbStairs(n - 1) + climbStairs(n - 2);
    }
    

    但直接进行递归在leetcode 上的测试没有通过,给的理由是Time Limit Exceeded

    尝试博客中的第二种方法:

    共有1级的时候有1种可能,n=1时 res[1]=1;

    共有2级的时候有2种可能,n=2时res[2]=2;

    共有3级的时候等于最后一步走了1级的可能结果res(2) 加上最后一步走了两级的可能结果res(1) ,即 n=3时res[3]=res(2)+res(1);

    所以有循环 res[n]=res(n-1)+res(n-2);

    int Solution::climbStairs(int n) {
    	
    	//利用递归和循环的转换
    	if (n == 1) return 1;
    	if (n == 2) return 2;
    	vector<int> res;
    	res.push_back(1);
    	res.push_back(2);
    	for (int i = 2; i < n ; i++)
    	{
    		res.push_back(res.at(i - 1) + res.at(i - 2));
    	}	
    	return res.back();// .at(n - 1);
    }
    

    通过了,在博客中还指出了使用空间问题,确实,在代码执行的过程中只用到最后三个,而且最终的输出也只是最后一个,所以空间完全可以重复利用。

  • 相关阅读:
    xp系统优化
    项目开发文档格式13种 (转载)
    java 操作 ORACLE
    orclae temp table
    把EXCEL上传并BINDING到GRIDVIEW中
    从excel读数据写入数据库代码
    GMDatePicker控件的使用
    代码汇总
    dwr运行时出现Servlet.init() for servlet dwrinvoker threw exception的解决方法
    CVSNT安装
  • 原文地址:https://www.cnblogs.com/simayuhe/p/6807415.html
Copyright © 2020-2023  润新知