无重复字符子集问题

Description
Mike is a lawyer with the gift of photographic memory. He is so good with it that he can tell you all the numbers on a sheet of paper by having a look at it without any mistake. Mike is also brilliant with subsets so he thought of giving a challange based on his skill and knowledge to Rachael. Mike knows how many subset are possible in an array of N integers. The subsets may or may not have the different sum. The challenge is to find the maximum sum produced by any subset under the condition:

The elements present in the subset should not have any digit in common.

Note: Subset {12, 36, 45} does not have any digit in common and Subset {12, 22, 35} have digits in common.Rachael find it difficult to win the challenge and is asking your help. Can youhelp her out in winning this challenge?

Input
First Line of the input consist of an integer T denoting the number of test cases. Then T test cases follow. Each test case consist of a numbe N denoting the length of the array. Second line of each test case consist of N space separated integers denoting the array elements.

Constraints:

1 <= T <= 100

1 <= N <= 100

1 <= array elements <= 100000

Output
Corresponding to each test case, print output in the new line.

Sample Input 1
1
3
12 22 35

Sample Output 1
57

# 无重复字符子集问题。动态规划解决
# 还未加入的数字集合、已经加入的数字的set集合、结果元素和
def solution(l, s, res):
    # 每次都面临两个选择:1.在已经存在的集合中加入当前元素(前提是已经存在的集合中没有该元素数字),2.不加入
    if len(l) == 0:
        return res
    else:
        temp = l[0]
        temp_set = set()
        s2 = set()
        # 判断temp中的字符是否在s集合中,如果没有在,一种方法是将temp加入到已经存在的数字集合中,另一种方法是跳过
        # 如果已经存在了,那么直接跳过
        for i in str(temp):
            temp_set.add(i)
        if len(temp_set.intersection(s)) == 0:
            s2 = s.union(temp_set)
            return max(solution(l[1:], s2, res + temp), solution(l[1:], s, res))
        else:
            return solution(l[1:], s, res)


if __name__ == '__main__':
    n = int(input())
    for i in range(n):
        number = int(input())
        l = list(map(int, input().strip().split()))
        # 已经加入集合中的元素集
        s = set()
        # 结果元素和
        res = 0
        result = solution(l, s, res)
        print(result)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值