"070-climbing Stairs (climbing stairs)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
You is climbing a stair case. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In what many distinct ways can you climb to the top?
Main Topic
You are climbing a staircase, to go to the top of the N-step, each time you can walk two or one step, how many different ways you climb to the top.
Thinking of solving problems
Solution one: With the combination of the number of ideas to solve, sub-conditions, there is no one walk two steps of C (0, N), only one walk two steps C (1, n-1), only two times to walk two steps, C (2, n-2), until only [N/2] (down to take the whole) go two steps. And it is all the solution.
Solution Two: Using the Division method, to N steps, with an array to save its solution, a[1] = 1,a[2] = 2, K >= 2, there is a[k] = a[k-1]+a[k-2].
Code Implementation
Algorithm implementation class, solution one
Public class solution { Public int Climbstairs(intN) {if(N <0) {return 0; }Else{intresult =0; for(inti =0; I <= N; i++, n--) {result + = combination (i, n); }returnResult } }/** * for combinations * * @param sup superscript * @param Sub subscript * @return Results */ Private int Combination(intSupintSub) {if(Sup > Sub | | sup <0|| Sub <0) {Throw NewRuntimeException ("Error args"); }if(sup = =0) {return 1; }if(Sup > Sub/2) {sup = Sub-sup; }Longx =1;//The product of the denominator Longy =1;//The product of the molecule LongZ for(inti =1; I <= sup; i++) {x *= (sub-i +1); Y *= i; z = gcd (x, y);//Find greatest common divisor //Numerator denominator shrinks the maximum number of conventions several timesx/= z; Y/= Z; }return(int) (x/y); }Private int GCD(LongMinLongMax) {Longtmpif(Max < min) {tmp = min; min = max; max = tmp; } while(max% min! =0) {tmp = min; min = max% min; max = tmp; }return(int) min; }}
Algorithm implementation class, solution two
Public classSolution { Public int Climbstairs(intN) {intresult =0;//Only one order if(n = =1) {result =1; }//Only two-stage Else if(n = =2) {result =2; }//stair order greater than 2 Else if(N >2) {//Save All Solutions int[] ways =New int[n]; ways[0] =1; ways[1] =2; for(inti =2; i < ways.length; i++) {Ways[i] = ways[i-1] + ways[i-2]; } result = Ways[ways.length-1]; }returnResult }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Solution One
Solution Two
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47247995"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
leetcode-Interview Algorithm classic-java Implementation "" 070-climbing Stairs (stair climbing)