剑指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;
    }
}
相关文章
相关标签/搜索