DFS notes
Last updated
Last updated
'a' 'b' 'c'
0 0 0
1 1 1
2
3 input: {1,1,2}
{}(1,1,2)
/ -------|--------- \ \
{1}(1,2) | {1}(2) | {2}() {}()
/ | \ | / \ |
{1,1}(2) {1,2}() {1}() | {1,2}() {1}()|
/ \ ----------------- 这一支可以剪掉
{1,1,2}() {1,1}() 结果必然重复
每次进入下层递归会先check当前路径,这个操作相当于是在该层一个数字都不选,即为上图中每层的空元素。 "" _________
/ | \ |
/ | \ | 因为没有与之相配的 “(”,这部分被 prunning
"(" | ")" |
/ \ ---------
/ \
"((" "()"_______
/ \ / | \ |
"(((" "(()" "()(" | "())"| 被剪枝
--------
... 1 5 10 25
------------------------------------
0 0 0 0
1 1 1 1
2 2 2 ...
3 3 3
... ... ...
99 input:(1,2,3)
{}(1,2,3)
/ | \
/ | \
/ | \
L1: {1}(2,3) {2}(1,3) {3}(1,2)
/ \ / \ / \
/ \ / \ / \
L2: {1,2}(3) {1,3}(2) {2,1}(3) {2,3}(1) {3,1}(2) {3,2}(1)
| | | | | |
L3: 123 132 213 231 312 321# list<char> input, int pos
def dfs(input, pos):
if pos == len(input):
# store this input as a result
return
for i in range(pos, len(input)):
swap(input, pos, i) # 将选定的换到第pos位
dfs(input, pos + 1) # 向后进行,因为第pos位已经确定
swap(input, pos, i) # back tracking