Tail Recursion
# recursion
public int factorial(int n) {
if (n == 1) {
return 1;
}
return n * factorial(n-1);
}
# non recursion
public int fatorial(int n) {
int sum = 1;
for (int i = 1; i <= n; i++) {
sum *= i;
}
return sum;
}
recursion 和 for loop 相比没有什么优势,只是代码更少一些。
recursion 一般都可以转换成 for loop。
Core Problem with Recursion
- Base case
- Recursion Rules
- Represent the problem with coding function
- Define the essential paramaters
- Paramaters that define the problem
- Paramaters that store the temporary result or state
- Define the return value
Classical Recursion Problem
- Fibonacci Number
- Climbing Stairs
- Merge Sort
- Towers of Hanoi
- Binary Search
LC89: Gray Code
输入是n,可以产生 2^n 个数字.
n = k, 有 2k 个数,从 0 - 2k-1
n = k+1,有 2k+1 个数,从 0 - 2k
Recursion Rule: 从 k 到 k+1 的recursion rule是:把 k 的组合数列反转,然后每个数字 +2k. 比如 k = 2, {0,1,2,3} 的合法排列之一是 [0,1,3,2] ; 反转得到 [2,3,1,0] , 每个数字 + 22 得 [6,7,5,4]. 2 和 6 只差一个 bit 位,因为6是2 + 22 得到的。得到 k + 1 = 3 时 {0,1,2,3,4,5,6,7} 的合法排列 [0,1,3,2,6,7,5,4] .
原始 input 不能满足 recursion 的需求时,helper function可以满足输入更多的 input . 把temp result 放在helper function Parameter里优于将其放置为global variable.
Base Case: n = 0, output = [0]
public List<Integer> grayCode(int n) {
List<Integer> result = new ArrayList<>();
helper(n, helper);
return result;
}
public void helper(int n, List<Integer> result) {
// base case
if (n == 0) {
result.add(0);
return;
}
// get result for n-1
helper(n-1, result);
// do recursion rule
int size = result.size();
int k = 1 << (n - 1); // k = 2^n-1
// from result to base case
for (int i = size - 1; i >= 0; i--) {
result.add(result.get(i) + k);
}
return;
}
# non recursion
public List<Integer> grayCode(int n) {
List<Integer> result = new ArrayList<>();
result.add(0);
for (int i = 0; i < n; i++) {
int k = 1 << i;
int size = result.size();
for (int j = size - 1; j >= 0; j--) {
result.add(result.get(j) + k);
}
return result;
}
}
0-1 Knapsack
Example Input: s = 20; w = [14, 8, 7, 5, 3]
Example Output: True
public static boolean knapsack (int s, int[] weights, int i) {
// good base case: s = 0, pick nothing
if (s == 0) {
return true;
}
// bad base case
if (s < 0 || i >= weights.length) {
return false;
}
// recursion rule
return knapsack(s - weights[i], weights, i + 1) ||
knapsack(s, weights, i + 1);
}
LC490: The Maze
public boolean maze(int[][] maze, int startX, int endY,
int targetX, int targetY,
boolean visited) {
}
1387




被折叠的 条评论
为什么被折叠?



