劍指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);
    }
}

  遞歸比循環簡單,但時間消耗更大,遞歸不斷調用函數,需求大。node

一隻青蛙一次能夠跳上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;
    }
}
相關文章
相關標籤/搜索