leetcode 70. Climbing Stairs Java解法,Amazon面试

Leetcode amazon 面试题系列(一) 最近在刷亚麻的面试题,然后顺便想练一练python的技巧,所以就用python刷了一边。然后mark一下以后可以复习。leetcode 771.大概就是给定两个字符串a 和b,问b 中出现了多少次a 的字符。记录一个python的用法:def numJewelsInStones(self, J, S): return sum(map(J.count, S))这里利用了 python 的几个... 阅读详情

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.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

My approach

class Solution {
    public int climbStairs(int n) {
        // use dynamic programming to avoid computing same value repeatedly
        if(n==0||n==1) return 1;
        int[] nums = new int[n+1];
        nums[0] = 1;
        nums[1] = 1;
        for(int i=2;i<n+1;i++){
            nums[i] = nums[i-1]+nums[i-2];
        }
        return nums[n];
    }
}

分析:

这道题还是考察递归的思想,观察到climbStairs(n) = climbStaris(n-1)+climbStairs(n-2)之后,可以写出简单的递归答案如下:

class Solution {
    public int climbStairs(int n) {
        if(n<0) return 0;
        if(n==0) return 1;
        if(n==1) return 1;
        if(n==2) return 2;
        return climbStairs(n-1) + climbStairs(n-2);
    }
}

但是如果这样做的话,会重复计算很多元素,造成时间的浪费。

所以考虑dynamic programming 的方法,将每次算的结果保存在一个数组里,如前面的解答所示。

问题升级版:

不光给n, 还给一个可以走的步数的集合X, 比如X={1,3,5},意味着在每个楼梯可以走1步3步或者5步。

未完待续。

 

亚麻 OA 2019 题目 Most Common Word Prison Cells After N Days K Closest Points to Origin Reorder Log Files Partition Labels Min Cost to Add New Roads Min distance to remove the obstacle Roll Dice Min Cost to Con... 阅读详情

相关推荐

Leetcode 250. Count Univalue Subtrees 谷歌面试, Java解法详解

这是一道谷歌会考的题目 Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of the subtree have the same value. Example : Input: root = [5,1,5,5,5,null,5] ...

YuanTheCoder的博客 463

LeetCode——Climbing Stairs

LeetCode——Climbing Stairs # 70 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 t

BigSea 346

几道亚马逊面试题参考答案

以前给别人写的几道亚马逊面试题参考答案。题目在源代码文件内。

LeetCode 273. Integer to English Words - 亚马逊高频题12

根据限制条件我们知道给定的是一个32位非负整数,即范围是0~2147483647,也就是说最大就是10亿(Billion)级别的。另外我们知道英文对数的书写是每隔三位用一个逗号,即每隔三位换一种表达(Thousand, Million, Billion)。也因此一个数的每一位的英文表达是:个、十,百、个千、十千、百千、个百万、十百万、百百万、个十亿、十十亿、百十亿。

hgq522的博客 771

Amazon面试在线测试题汇总

amazon online assignment summary

LeetCode各公司题目合集

LeetCode各公司题目合集~~Google uber linkedin amazon

leetcode amazon 面试题(三)

leetcode 21.  merge two sorted lists大概的意思就是 给两个list, 然后把它们按照所有元素的 从小到大的顺序排序。这里分享一个比较简洁的写法:class Solution(object): def mergeTwoLists(self, l1, l2): dummy = cur = ListNode(0) while l...

TonyYang1995的博客 1344

Amazon亚麻 最新leetcode tag题

amazon 2017年末更新的leetcode tag题,超全!准备亚麻面试的同学有用~

java 动态规划 斐波那契 和 爬楼梯问题

斐波那契 class Solution { public int fib(int n) { if(n<2) return n; int[] arr = new int[n+1]; arr[0] = 0; arr[1] = 1; for(int i = 2;i<= n;i++){ arr[i] = arr[i-2]+arr[i-1]; } return a

qq_54494937的博客 241

利用docx4j与docx4j-ImportXHTML高效实现HTML到Word的自动化转换

本文详细介绍了如何利用docx4j与docx4j-ImportXHTML库,在Java环境中高效实现HTML到Word文档的自动化转换。内容涵盖从环境搭建、核心依赖配置,到集成Spring Boot REST API的完整实战流程,并深入解析了处理图片、CSS样式、字体设置以及使用模板保证样式统一等高级技巧与常见问题解决方案,帮助开发者构建稳定的文档自动化生成流水线。

cnn8visionary的博客 365

BioEmu:微软黑科技炸场!生成式AI重构蛋白质模拟:千倍效率碾压传统计算,新药研发周期砍半

BioEmu 是微软推出的生成式深度学习系统,可在单个 GPU 上每小时生成数千种蛋白质结构样本,支持模拟动态变化、预测热力学性质,并显著降低计算成本。

士多啤梨先生の博客 1098

LeetCode 1229. Meeting Scheduler - 亚马逊高频题32

​ 这题其实就是一道典型的关于间隔的题。跟LeetCode 759. Employee Free Time非常相似,因此可以用类似的优先级队列的解法,具体的解题思路可以参考LeetCode 759. Employee Free Time。然而,题目说的只是两个人的会面,即只要从两个数组中找出有重叠且长度超过duration的时间间隔,因此可以用双指针法。

hgq522的博客 1200

Postman调试海康ISAPI接口全记录:从鉴权失败到成功修改设备名的踩坑指南

本文详细记录了使用Postman调试海康ISAPI接口的全过程,从鉴权失败到成功修改设备名的实战经验。涵盖Digest认证机制、XML请求体构造、常见错误排查及代码实现过渡,帮助开发者高效解决海康设备集成中的各种问题。

weixin_42620913的博客 660

亚马逊面试题1(数组)

题目:给定一个整型数组,里边包含正数和负数,求正负数之差的最大值,要求复杂度为Ο(n) S = a[i] - a[j] ,i>j且S > 0 #include #include using namespace std; int main() { int A[]={-2,-3,5,-6,8,-5,10,12,-16}; int max; int sum = INT_M

Bruce Lee的专栏 2159

MoveIt2项目想换掉KDL求解器?试试这个trac_ik插件(附源码编译避坑指南)

本文详细介绍了如何在MoveIt2项目中用trac_ik插件替代KDL求解器,提升机械臂运动学求解的效率和成功率。内容涵盖环境准备、源码编译避坑、项目集成及性能调优,特别适合需要高精度控制的协作机械臂应用场景。通过实测数据对比,trac_ik在求解时间和奇异点处理上显著优于传统KDL求解器。

weixin_30730053的博客 694

Material Studio 2024安装避坑指南:从证书配置到权限设置的完整解决方案

本文详细解析了Material Studio 2024的安装流程,从环境准备到权限优化的完整解决方案。针对证书配置、系统权限和计算服务等常见问题,提供了12个关键风险点的避坑指南,帮助科研工作者高效完成安装,提升材料模拟工作的效率。

moon9的博客 772

Leetcode 1086. High Five Java 解法

先吐槽一下这个难度,咋也不能是easy啊,和其他easy的不在一个量级。 Given a list of scores of different students, return the average score of each student'stop five scoresinthe order of each student's id. Each entryitems[i]h...

YuanTheCoder的博客 1473

多GPU时代的虚拟内存革命:CUDA VMM API的跨设备协同设计哲学

本文深入探讨了NVIDIA CUDA VMM API在多GPU系统中的虚拟内存管理革命,解决了传统Peer Access的显存碎片化和同步开销问题。通过地址-内存解耦、按需映射和精细权限控制,VMM API为分布式训练提供了高效的内存协同方案,显著提升大模型训练性能。

weixin_29251337的博客 534

Leetcode 1051. Height Checker, Java解法

Students are asked to stand in non-decreasing order of heights for an annual photo. Return the minimum number of students not standing in the right positions. (This is the number of students that mu...

YuanTheCoder的博客 649

手把手教你用DSP28335的PWM移相功能搞定双有源桥DAB(附完整代码)

本文详细解析了DSP28335的PWM移相功能在双有源桥DAB中的应用,包括ePWM模块的配置、移相时序原理及实战代码。通过精确的移相控制,实现DAB的高效运行和软开关,适用于车载充电机、储能系统等场景。附完整代码,助力开发者快速掌握硬件级移相技术。

weixin_30632089的博客 420

深度学习图神经网络 (GNN) —— 处理图结构数据(六十九)

本文系统介绍了图神经网络(GNN)的核心概念、主流模型及其应用。主要内容包括: GNN基础:阐述了图结构数据的特性(节点数不定、连接不规则),以及GNN相比CNN/RNN的优势在于处理非欧式空间的图数据。 核心机制:重点讲解了消息传递框架(MPNN),通过聚合邻居信息迭代更新节点表示,并分析了GCN的归一化邻接矩阵计算和GAT的注意力权重机制。 典型模型: GCN:基于归一化邻接矩阵的特征传播 GAT:引入注意力机制区分邻居重要性 GraphSAGE:通过采样解决大图扩展性问题 GIN:理论表达能力最强的图

hello.reader 300

Leetcode 1108. Defanging an IP Address, Java解法

Given a valid (IPv4) IPaddress, return a defanged version of that IP address. AdefangedIP addressreplaces every period"."with"[.]". Example 1: Input: address = "1.1.1.1" Output: "1[.]1[....

YuanTheCoder的博客 574

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Java中 Queue队列的用法及例子

1. Usage 用法 // "static void main" must be defined in a public class. public class Main { public static void main(String[] args) { // 1. Initialize a queue. Queue<Integer> q...

YuanTheCoder的博客 557

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

Leetcode 509. Fibonacci Number , Java 解法

TheFibonacci numbers, commonly denotedF(n)form a sequence, called theFibonacci sequence, such that each number is the sum of the two preceding ones, starting from0and1. That is, F(0) = 0, F(...

YuanTheCoder的博客 503

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

Leetcode 977. Squares of a Sorted Array, Java解法

Given an array of integersAsorted in non-decreasing order,return an array of the squares of each number,also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,1...

YuanTheCoder的博客 497

狗家 Online Assessment

License Key Formatting Unique Email Addresses Fruit Into Baskets Odd Even Jump Maximum Area Serving Cake Min Days to Bloom Fill Matrix Compare Strings Largest Subarray Length K Decreasing Sub...

YuanTheCoder的博客 470
上一篇: Leetcode 250. Count Univalue Subtrees 谷歌面试, Java解法详解
下一篇: Leetcode 38. Count and Say Java解法
YuanTheCoder
博客等级 码龄9年 2粉丝 34原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值