递归想了想差不多能够分清楚有哪些题型了
1)和回溯相关
1.深度优先搜索
IP地址的可能排列
dfs(s,tmp,index,res)
一般都是这样的格式,就是,第一个参数是输入原始参数,比如数啊,string啊之类的,tmp是临时的结果组合,index是组合到了什么程度,就是跳出递归的条件,最后res是存放每次递归的tmp结果的
1,leetcode#93
Restore IP Addresses
输入: “25525511135”
输出: [“255.255.11.135”, “255.255.111.35”]
|
|
2.比较巧妙的递归,在递归中设置激活按钮
1,leetcode#695
Max Area of Island
Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
12345678 [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]return 6
|
|
这一题需要流程的想象,比如上面例子中遍历到grid(0,6),他会先关闭递归的触发条件,然后进入递归,这样就不会重复递归
3.回溯法
比如比较常见的permutation
input 123
output [123,132,213,231,312,312]
|
|
采用回溯法一定要注意res.append的结果一定要是tmp的复制而不是,指针就是一定要加上[:]