题解 | #称砝码#

称砝码

http://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c

python的两种方法,第一种先把所有重量加到列表,再求全排列;第二种每添加一次数,求一次。

ms = input().strip().split(' ')
ms = [int(i) for i in ms]
counts = input().split(' ')
counts = [int(i) for i in counts]

def fun1():
    res = []
    res2 = []
    for i in range(n):
        res.extend([ms[i]]*counts[i])

    res_len = len(res)
    res2.append(res[0])
    for i in range(1,res_len):
        res2 = list(set(res2))
        res2_len = len(res2)
        res2.append(res[i])
        for j in range(res2_len):
            res2.append(res[i]+res2[j])
    print(len(set(res2))+1)
fun1()

def fun2():
    res = [ms[0]*k for k in range(1,1+counts[0])]
    for i in range(1,n):
        new = [ms[i]*k for k in range(1,1+counts[i])]
        res_len=len(res)
        new_len=len(new)
        for g in range(new_len):
            for j in range(res_len):         
                res.append(res[j]+new[g])
        res.extend(new)
        res = list(set(res))
    print(len(set(res))+1)
#fun2()
全部评论

相关推荐

点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务