On the code first:
def fib (nlist,res): print_list = [] print_list.extend (res) print_list.append (nlist if not nlist else nlist [0]) If Len (nlist) ==1: print ' ############ #print_list ', print_list return temp_list = [] temp_ List.extend (nlist) for i in range (len (temp_list)): fib (temp_list[i+1:],print_list) # fib ([1,2,3,4, '],[]) Nlist = [1,2,3,4, ']for I in range (4): fib (nlist[i:],[])
Results:
C:\Python27\python.exe d:/work/search/2.py############ #print_list [1, 2, 3, 4, ']############ #print_list [1, 2, 3, ']# ########### #print_list [1, 2, 4, ']############ #print_list [1, 2, ']############ #print_list [1, 3, 4, ']############ #p rint_list [1, 3, ']############ #print_list [1, 4, ']############ #print_list [1, ']############ #print_list [2, 3, 4, '] ############ #print_list [2, 3, ']############ #print_list [2, 4, ']############ #print_list [2, ' ']############ #print_ list [3, 4, ']############ #print_list [3, ']############ #print_list [4, ']process finished with exit code 0
Realization idea: Multi-fork tree, see figure
The reason is to use the multi-fork tree implementation, is because before reading a recursive article, said that recursion is mainly used in the scene is divided into two, is to think up and say
Recursion is the main process must be correct, I understand that, as long as the demand can be drawn into a tree, you can sort out the process of recursion (of course, the two conditions to meet the recursion)
The two conditions for recursion are (quoted):
- The problem size can be narrowed by recursive invocation, and the new problem has the same form as the original problem.
- There is a simple situation in which recursion can be exited in a simple context.
How to turn a tree into a recursive process, record it, and make it easier to see later
1 function The first argument must have a decrement attribute, or it won't end.
2 function The second parameter is used to collect the node and then output the result at the leaf so that a branch can be recorded
3 This function is not the final function, each node should be the next tree, you need to record its branches (in the outside to do a decrement for loop implementation, so do not add redundancy, because each node is running, currently do not consider the redundancy problem, consider the words will not go recursive)
It is said that recursion can be implemented iteratively, for example, with the yield generator, which is later studied
can also be achieved through the tree traversal, the tree has not been studied, and later
There is also a binary tree traversal, which is recorded first and later studied
Recursive implementation of combinations with Python, and personal impressions about recursion