Editorial for Possible Number


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: EricLai

法一

def possible_num(nums,k):
    ans = []
    def helper(nums,k,tmp):
        if k == 0:
            ans.append(tmp)
        else:
            for i,v in enumerate(nums):
                helper(nums[i+1:],k-1,tmp+v)
    helper(nums,k,0)
    return sorted(ans)
T = int(input())
for t in range(1,T+1):
    n,k = map(int,input().split())
    nums = [2**i for i in range(n)]
    print(f'Case #{t}: {possible_num(nums,k)}')

法二

def possible_num(n):
    record = {i:[] for i in range(n+1)}
    for i in range(1<<n):
        cnt = 0
        num = i
        while i > 0:
            cnt += (1 & i)
            i = i>>1
        record[cnt].append(num)

    return record


ans = {i:possible_num(i) for i in range(1,17)}

T = int(input())
for i in range(1,T+1):
    n,k = map(int,input().split())
    print(f'Case #{i}: {ans[n][k]}')

法三

from itertools import combinations

T = int(input())
for i in range(1,T+1):
    n,k = map(int,input().split())
    nums = [2**i for i in range(n)]
    ans = sorted(list(map(sum,combinations(nums,k))))
    print(f'Case #{i}: {ans}')

Comments

There are no comments at the moment.