剑指offer_2.3_Day_6
生活随笔
收集整理的這篇文章主要介紹了
剑指offer_2.3_Day_6
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項(從0開始,第0項為0)。
n<=39
public class Solution {
public int Fibonacci(int n) {
int a=1,b=1,c=0;
if(n<0){
return 0;
}else if(n==1||n==2){
return 1;
}else{
for (int i=3;i<=n;i++){
c=a+b;
b=a;
a=c;
}
return c;
}
}
}
public class Solution {
public int Fibonacci(int n) {
if(n==0)
return 0;
else if(n==1)
return 1;
else
return Fibonacci(n-1)+Fibonacci(n-2);
}
}
遞歸比循環簡單,但時間消耗更大,遞歸不斷調用函數,需求大。
一只青蛙一次可以跳上1級臺階,也可以跳上2級。求該青蛙跳上一個n級的臺階總共有多少種跳法(先后次序不同算不同的結果)。
依舊是斐波那契,如題可知,每次1或者2級臺階,假設最后一次跳了1階臺階,剩下的就是跳了n-1此臺階的跳法,如果最后跳了2級臺階,那就是剩下n-2臺階的跳法,也就是n級臺階等于n-1+n-2兩種臺階跳法的總和。
public class Solution {
public int JumpFloor(int target) {
if(target <= 0) return 0;
if(target == 1) return 1;
if(target == 2) return 2;
int one = 1;
int two = 2;
int result = 0;
for(int i = 2; i < target; i++){
result = one+ two;
one = two;
two = result;
}
return result;
}
}
一只青蛙一次可以跳上1級臺階,也可以跳上2級……它也可以跳上n級。求該青蛙跳上一個n級的臺階總共有多少種跳法。
同上,只不過改成了加起來所有的,可以留一個數組來保存。
public class Solution {
public int JumpFloorII(int n) {
int [] ans = new int [n+1];
if(n==0)
return 0;
ans[0]=1;ans[1]=1;
for(int i=2;i<=n;i++)
{
ans[i]=0;
for(int j=0;j<i;j++)
{
ans[i]+=ans[j];
}
}
return ans[n];
}
}
我們可以用2*1的小矩形橫著或者豎著去覆蓋更大的矩形。請問用n個2*1的小矩形無重疊地覆蓋一個2*n的大矩形,總共有多少種方法?
public class Solution {
public int RectCover(int target) {
if(target==0){
return 0;
}
else if(target==1)
{
return 1;
}
else if(target==2){
return 2;
}else{
return RectCover(target-1)+RectCover(target-2);
}
}
}
在一個排序的鏈表中,存在重復的結點,請刪除該鏈表中重復的結點,重復的結點不保留,返回鏈表頭指針。 例如,鏈表1->2->3->3->4->4->5 處理后為 1->2->5
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead !=null && pHead.next == null){
return pHead;
}
ListNode preNode =null;
ListNode node = pHead;
while(node != null){
if(node.next !=null && node.val == node.next.val){
while(node.next != null && node.next.val == node.val){
node = node.next;
}
if(preNode == null){
pHead = node.next;
}else{
preNode.next = node.next;
}
}else{
preNode = node;
}
node = node.next;
}
return pHead;
}
}
總結
以上是生活随笔為你收集整理的剑指offer_2.3_Day_6的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 丑憨批的NLP笔记BERT前置:ATUO
- 下一篇: 四、java基础-面向过程_对象_类中可