Learn Python from the doll! 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】
Arrangement and combination are commonly used mathematical methods, where combination is to extract r elements from n elements (regardless of order and r≤n), we can simply understand n elements as natural numbers 1, 2,..., n, from which r numbers are chosen arbitrarily.
You are now asked to output all combinations.
For example n=5, r=3, all combinations are:
123,124,125,134,135,145,234,235,245,345.
【Enter description】
A row of two natural numbers n, r (1<n≤21, 0≤r≤n).
【Output description】
For all combinations, each combination occupies one line and its elements are arranged in ascending order, each element occupies a position of three characters, and all combinations are also in lexicographical order.
【Sample input】
5 3
【Sample output】
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
【Code Explanation】
n,r = [int(i) for i in input().split()]
arr = [0 for i in range(n+1)]
def dfs(x, start):
if x > r:
for i in range(1, r+1):
print(' '+str(arr[i]), end='')
print()
return
for i in range(start, n+1):
arr[x] = i
dfs(x+1, i+1)
arr[x] = 0
dfs(1, 1)
复制代码
【operation result】
5 3
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5