多少种取法

所属作业: hw7 算法: 递归

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def count_ways(m, n, s):
    if n == 0 and s == 0:
        return 1
    if n == 0 or s <= 0 or m <= 0:
        return 0
    # 递归调用,分两种情况:包含第m个数和不包含第m个数
    ways_with_m = count_ways(m - 1, n - 1, s - m)
    ways_without_m = count_ways(m - 1, n, s)
    return ways_with_m + ways_without_m
# 输入处理
t = int(input())
for _ in range(t):
    m, n, s = map(int, input().split())
    result = count_ways(m, n, s)
    print(result)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def ways(m,n,s):
    #special 
    if m<n:    
        return 0
    elif m>=n and s==0:   
        return 0
    elif m==0 and (s!=0 or n!=0):
        return 0
    elif n==0 and s==0:     
        return 1
    elif n==0 and s>0:     
        return 0
    elif n==1:           
        if m>=s:return 1   #若m>=s,只有1种取法
        else:return 0     #若m<s,则取法为0
    
    elif n>1 and s==1:   #当n>1且s=0时 ,取法为0
        return 0
    
   
    elif m>s:          
        if n == s or n>s:
            return 0
        elif 1<n<s:
            return ways(s-1,n,s)
    elif m<s:          
        return ways(m-1,n-1,s-m)+ ways(m-1,n,s)  #当取m时 与 不取m时 的和
    elif m == s :  
        if n>m:
            return 0
        else:
            return ways(m-1,n,s)
        
x = int(input())
b=[]
for i in range(x):
    m,n,s = map(int,input().split())
    b.append(ways(m,n,s))
for j in b:
    print(j)