剑指offer-day8
斐波那契数列
递归经典题目,但是使用传统递归会超时,需要使用优化的记忆递归。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public int fib(int n) { int a = 0; int b = 1; int sum = 0; for(int i = 0; i < n; i++){ sum = (a + b) % 1000000007; a = b; b = sum; } return a; } }
|
青蛙跳台阶
其实就是斐波那契数列,只要记住上一题的解法,这道题就是一模一样,只是初始条件改变了。
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution { public int numWays(int n) { int a = 1; int b = 1; int sum = 0; for(int i = 0; i < n; i++){ sum = (a+b) % 1000000007; a = b; b = sum; } return a; } }
|
股票的最大利润
这道题用动态规划没有想出来,看了答案才发现原来这么淳朴…大体思路是遍历整个数组,记录一个最低价,如果后面有更低的价格就更新最低价;没有的话就计算差值,差值最大即为答案。
1 2 3 4 5 6 7 8 9 10 11
| class Solution { public int maxProfit(int[] prices) { int cost = Integer.MAX_VALUE; int profit = 0; for(int price : prices){ cost = Math.min(price,cost); profit = Math.max(profit,price - cost); } return profit; } }
|