【算法】MVP 争夺战

题干:MVP 争夺战题目描述

在星球争霸篮球赛对抗赛中,强大的宇宙战队,希望每个人都能拿到MVP。
MVP 的条件是,单场最高分得分获得者,可以并列,所以宇宙战队决定在比赛中,尽可能让更多的队员上场,日让所有有得分的队员得分都相同。然而比赛过程中的每一分钟的得分都只能由某一个人包揽。

输入描述

输入
第一行为一个数字t,表示有得分的分钟数( 1<=t<=50),
第二行为t个数字,代表每一分钟的得分p(1<=p<=50)

输出描述

输出有得分的队员都是 MVP 时最少的 MVP 得分。

《将数组分割成和相等的数组》 leetcode难度 hard(1分2)
本题是《将数组分割成最多个和相等的数组》,(1分N)

import time
start = time.time()

nums = [5,5,5,2,2,2,1,1,1]
# nums = [2,5,1,2,2,5,1,5,1]
# nums = [3,2,4,3,6]
def get_factors(num):
    factors = []
    for i in range(1, num+1):
        if num % i == 0:
            factors.append(i)
    return factors
sums = sum(nums)
factors = get_factors(sums)
Global_Target = []

# 先加出来1个因子
# 然后把因子设为target,让后面的计算去拟合target,超于target的直接退出
def find_next_sum(cur_sum,cur_nums,target = None,match_num = 0):
    global Global_Target
    if len(cur_nums) == 0:
        if target is None:
            return 0,0
        if (target * (match_num + 1) != sums):
            return 0,0
        if target not in Global_Target:
            print (f"hit {target}")
            Global_Target.append(target)
        return target,match_num
    #必须要把数全部用完才有max_match_num
    max_match_num = 0
    max_target = target
    for i in range(len(cur_nums)):
        new_tar = cur_sum + cur_nums[i]
        #多个子数组
        if target is not None and target == new_tar:
            cur_target , cur_max_match_num = find_next_sum(0,cur_nums[:i] + cur_nums[i+1:],target = new_tar,match_num = match_num + 1)
            if cur_max_match_num > max_match_num:
                 max_match_num = cur_max_match_num
                 max_target = cur_target
            break
        #找到新的target
        if target is None and new_tar in factors:
            cur_target , cur_max_match_num = find_next_sum(0,cur_nums[:i] + cur_nums[i+1:],target = new_tar)
            if cur_max_match_num > max_match_num:
                 max_match_num = cur_max_match_num
                 max_target = cur_target
        #target越界
        if new_tar > sums / 2:
            continue
        #累加过程
        cur_target , cur_max_match_num = find_next_sum(new_tar,cur_nums[:i] + cur_nums[i+1:],target = target,match_num = match_num)
        if cur_max_match_num > max_match_num:
            max_match_num = cur_max_match_num
            max_target = cur_target
    return max_target,max_match_num

cur_target , cur_max_match_num = find_next_sum(0,nums)
cur_max_match_num += 1
print (f"{cur_target},{cur_max_match_num}")        

end = time.time()
print (f"time cost:{end - start}")

使用DFS算法,未剪枝。

在这里插入图片描述

你可能感兴趣的:(算法,leetcode,职场和发展)