Given an array of distinct elements, the aim is to list all possible permutations of the array elements.
The following algorithm generates all permutations in O(N!) time complexity:
def permute(arr, i=0): if i == len(arr) - 1: print(arr) return for j in range(i, len(arr)): arr[i], arr[j] = arr[j], arr[i] permute(arr, i + 1) arr[i], arr[j] = arr[j], arr[i]
For arrays with repeated elements, the Jarvis March algorithm is a more efficient approach:
def permute_repeated(arr): ind = [0] * len(arr) for i in range(len(arr)): ind[i] = i while True: yield [arr[i] for i in ind] for i in range(len(arr) - 2, -1, -1): if ind[i] < ind[i + 1]: break if i == -1: return for j in range(len(arr) - 1, -1, -1): if arr[j] > arr[i]: ind[i], ind[j] = ind[j], ind[i] break ind[i + 1:] = sorted(ind[i + 1:])
The above is the detailed content of How to Generate All Permutations of an Array, Including Those with Repeated Elements?. For more information, please follow other related articles on the PHP Chinese website!