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级台阶,假设最后一次跳了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; } }
同上,只不过改为了加起来全部的,能够留一个数组来保存。函数
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]; } }
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); } } }
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; } }