Pupils Blue Bridge Cup Python breakthrough | DFS implements exponential enumeration

Learn Python from a baby! Record the questions in the Blue Bridge Cup Python learning and test preparation process, and record every moment.

Attached is a summary post: Pupils Blue Bridge Cup Python Breakthrough | Summary_COCOgsta's Blog-CSDN Blog


【Description】

Randomly select any number of n integers from 1 to n, and output all possible options.

【Enter description】

Enter an integer n.

【Output description】

Output one scheme per line.

Numbers in the same line must be arranged in ascending order, and two adjacent numbers are separated by exactly one space.

For schemes that do not choose any number, output a blank line.

【Sample input】

3

【Sample output】

3

2

2 3

1

1 3

1 2

1 2 3

【Code Explanation】

n = int(input())

st = [0 for i in range(n+1)] #记录每个数的状态,0表示还没考虑,1表示选,2表示不选

def dfs(x):
    if x > n:
        for i in range(1, n+1):
            if st[i] == 1:
                print(i, end=" ")
        print()
        return

    #不选
    st[x] = 2
    dfs(x+1)
    st[x] = 0 #恢复现场

    #选
    st[x] = 1
    dfs(x+1)
    st[x] = 0 #恢复现场

dfs(1)
复制代码

【operation result】

3

3 
2 
2 3 
1 
1 3 
1 2 
1 2 3 

Guess you like

Origin blog.csdn.net/guolianggsta/article/details/130493407