You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

'''
Author: SJ2050
Date: 2021-10-10 23:34:50
LastEditTime: 2021-10-16 23:23:48
Version: v0.0.1
Description: Solution for homework 2.
Copyright © 2021 SJ2050
'''
from itertools import permutations
def combination(arr, n):
if n == 0:
return [[]]
l =[]
for i in range(0, len(arr)):
m = arr[i]
remLst = arr[i + 1:]
for p in combination(remLst, n-1):
l.append([m]+p)
return l
def heapPermutation(arr, n, process):
if n == 1:
process(arr)
return
for i in range(n):
heapPermutation(arr, n-1, process)
if n & 1:
arr[0], arr[n-1] = arr[n-1], arr[0]
else:
arr[i], arr[n-1] = arr[n-1], arr[i]
if __name__ == '__main__':
nums = [1, 2, 3, 4]
m = 3
count = 0
combs = combination(nums, m)
def printAndCount(arr):
global count
count += 1
for i in range(len(arr)):
print(f'{arr[i]}', end='')
print('')
print('3-digit nums:')
for c in combs:
heapPermutation(c, m, printAndCount)
print('-'*12)
print(f'Total count: {count}')
# 从一列数中取出三个元素组成三位数的算法复杂度分析:
# 首先是组合分析从一列数中取出三个数的组合个数为n*(n-1)*(n-2)/6算法时间复杂度为O(n^3).
# 接着对每队组合进行排列排列算法选用的是heap算法其时间复杂度为O(n!).
# 故总的时间复杂度为: O((n^3)*(3!)) --> O(n^3)