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; } }