1. 爬楼梯
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
思路:分析题意可知,第三层的上楼方法是(第一层)与(第二层)的和。p[i] = p[i-1]+p[i-2].所以只需要使用for循环更新即可。
class Solution { public: int climbStairs(int n) { if(n==1) return 1; if(n==2) return 2; int first = 1; int second = 2; for(int i=3;i<=n;i++) { int third = first + second; first = second; second = third; } return second; } };参考链接:https://leetcode-cn.com/problems/climbing-stairs/
2.删除排序链表中的重复元素
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
思路:直接法,就使用将结点的值与它之后的结点进行比较来确定它是否为重复结点。如果它是重复的,我们更改当前结点的 next 指针,以便它跳过下一个结点并直接指向下一个结点之后的结点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode *current = head; while(current!=NULL && current->next!=NULL) { if(current->val == current->next->val) current->next=current->next->next; else current = current->next; } return head; } };参考链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
