规律:

Permutation:

Combination:

代码:

def permute(numbers):
    # 处理只有1个或0个元素的情况
    count = len(numbers)
    if count <= 1:
        return [] if count == 0 else [numbers]

    # 处理多个元素的情况 
    permutations = []       # 存储全排列结果

    for i in range(count):
        # 抽取第i个元素,原数组分为两部分:number_i 和 reminings
        number_i = numbers[i]
        remainings = numbers[:i] + numbers[i+1:]

        # 对剩余部分继续调用全排列递归操作
        for p in permute(remainings):
            permutations.append([number_i] + p)

    # 返回最终结果
    return permutations

def combine(numbers):
    if len(numbers) == 0:
        return [[]]
    # (5,1), (5, 2), ..., (5, 5)
    combinations = []
    first_num = numbers[0]
    remainings = numbers[1:]
    # 已有 n 个组合,再添加一个元素,增加n 种新的组合
    # 如 已有 [[], [1], [2], [1,2]],现在再增加一个3, 则:
    #  [[1], [2], [1,2]] + [[3], [1,3], [2,3], [1,2,3]], 即
    # []  -> [] + [3]
    # [1] -> [1, 2]
    # [2] -> [2, 3]
    # [1,2] -> [1,2,3]
    # PS,默认包括空集 []
    for sub_combination in combine(remainings):
        combinations.append(sub_combination)
        combinations.append([first_num] + sub_combination)
    #print(len(numbers), '->', len(combinations) ,combinations, '\n')
    return combinations

fp = lambda n : n * fp(n-1) if n > 1 else 1 

numbers = [1, 7, 3, 5, 6, 29, 13]
numbers = [1, 7, 3, 5, 6, 8]

#def fp(n):
#    return n * fp(n-1) if n > 1 else 1
permutations = permute(numbers)
combinations = combine(numbers) 

#for permutation in permutations:
#    print(permutation)

ns = len(numbers)
print('Permutations Total: ', len(permutations), ", expected number: ", fp(len(numbers)))
print('Combinations Total: ', len(combinations), ", expected number: unknown", 2**ns)
print([3]+[4,5])

# 工作内容拆分

fp = lambda n : n * fp(n-1) if n > 1 else 1 

numbers = [1, 7, 3, 5, 6, 29, 13]
numbers = [1, 7, 3, 5, 6, 8]

#def fp(n):
#    return n * fp(n-1) if n > 1 else 1
permutations = permute(numbers)
combinations = combine(numbers) 

#for permutation in permutations:
#    print(permutation)
ns = len(numbers)
print('Permutations Total: ', len(permutations), ", expected number: ", fp(len(numbers)))
print('Combinations Total: ', len(combinations), ", expected number: unknown", 2**ns)


# 工作内容拆分

输出

Permutations Total:  720 , expected number:  720
Combinations Total:  64 , expected number: unknown 64

results matching ""

    No results matching ""