


How to Generate All Permutations of an Array, Including Those with Repeated Elements?
Generating All Permutations of an Array
Given an array of distinct elements, the aim is to list all possible permutations of the array elements.
Algorithm
The following algorithm generates all permutations in O(N!) time complexity:
- Initialize: Set i = 0.
- Iterate over array: While i is less than the array length:
- Swap: Swap the element at index i with each of the remaining elements in the array.
- Recurse: Recursively call the algorithm with i 1 as the new i value.
- Swap back: After the recursive call, swap the element back to its original position.
- Increment i: Increment i by 1.
Python Implementation
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]
Jarvis March Algorithm
For arrays with repeated elements, the Jarvis March algorithm is a more efficient approach:
- Sort: Sort the array in ascending order.
- While: While not done:
- Find pivot: Find the largest index where the element is less than its successor.
- Find adjacent: Find the last element in the sorted portion that is greater than the element at the pivot index.
- Swap: Swap the elements at the pivot and adjacent indices.
- Reverse: Reverse the elements from the pivot index to the end of the sorted portion.
- Check done: Check if the array is sorted in descending order. If so, exit the loop.
Python Implementation
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

