学习目标:
总结recursion的规律和自己的应对方法学习内容:
1、 leetcode高频recursion25题学习时间:
1、 周一至周五晚上 7 点—晚上9点学习产出:
1、 技术笔记博客 1 篇==================================
帅地博客讲解recursion
基础题:
lc13
Evaluate a to the power of b, assuming both a and b are integers and b is non-negative.
recursion:
recursively将问题分解成小一号的问题。
power(a,b) --> power(a,b/2);
public class Solution {
public long power(int a, int b) {
if(a==0) return 0;
if(b==0) return 1;
long half=power(a,b/2);
if(b%2==0){
return half*half;
}else{
return half*half*a;
}
}
}
lc624
Get the Kth number in the Fibonacci Sequence. (K is 0-indexed, the 0th Fibonacci number is 0 and the 1st Fibonacci number is 1).
recursion:
recursively将问题分解成小一号的问题。
fibonacci(3)=fibonacci(2)+fibonacci(1)
“递归”中,随着k不断减小,
“递去”遇到最小元素,k=0,k=1在base case中都已经写好了。
“归来”的就是答案。
public class Solution {
public int fibonacci(int K) {
//base case
if(K<=0) return 0;
if(K==1) return 1;
//recursion rule
return fibonacci(K-1)+fibonacci(K-2);
}
}
优化:
dp的思想,用一个记事本,从最小元素开始,不断往大的元素推导。
public int fibonacci(int K) {
if(K<=0){
return 0;
}
long[] array=new long[K+1];
array[1]=1;
for (int i=2;i<K+1;i++){
array[i]=array[i-2]+array[i-1];
}
return (int)array[K];
}
//why use long here then cast to int?
//it is possible to get an overflowed number,
//and sometimes we will need to use something like BigInteger.
高频题:
395. Longest Substring with At Least K Repeating Characters
Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.
key insights:
这题中,将原问题longestSubstring(String s, int k)转成设定好边界的问题。longestSubstringUtil(s,0,s.length(),k);
然后用divide and conquer方法,将原问题分解成小一号的问题longestSubstringUtil(s,start,mid,k)和longestSubstringUtil(s,midnext,end,k)。
问自己三个问题:
Q1.子问题是什么?–> 以第1个不满足条件的char为分界点,切分大问题
Q2.当前层做什么?–> 对比两个子问题,谁的解更长,取max?
Q3.返回给上一层什么?–> 返回一个长度。
class Solution {
public int longestSubstring(String s, int k) {
//longestSustring(start, end)
//= max(longestSubstring(start, mid), longestSubstring(mid+1, end))
return longestSubstringUtil(s,0,s.length(),k);
}
public int longestSubstringUtil(String s, int start, int end,int k) {
if(end<k) return 0;
int[] countMap=new int[26];
for(int i=start;i<end;i++){
countMap[s.charAt(i)-'a']++;
}
for(int mid=start;mid<end;mid++){
if(countMap[s.charAt(mid)-'a']>=k){
continue;
}
int midnext=mid+1;
while(midnext<end && countMap[s