Я хочу, чтобы эффективный алгоритм нашел следующую большую перестановку данной строки.
Алгоритм для поиска следующей большей перестановки заданной строки
Ответ 1
В Википедии есть хорошая статья о генерации лексикографического заказа. Он также описывает алгоритм для создания следующей перестановки.
Цитирование:
Следующий алгоритм генерирует следующую перестановку лексикографически после данной перестановки. Он изменяет заданную перестановку на месте.
- Найти наивысший индекс
i
такой, чтоs[i] < s[i+1]
. Если такой индекс не существует, перестановка является последней перестановкой.- Найти наивысший индекс
j > i
такой, чтоs[j] > s[i]
. Такойj
должен существовать, так какi+1
- такой индекс.- Сменить
s[i]
с помощьюs[j]
.- Обратный порядок всех элементов после индекса
i
до последнего элемента.
Ответ 2
Отличное решение, которое работает, описано здесь: https://www.nayuki.io/page/next-lexicographical-permutation-algorithm. И решение, которое, если следующая перестановка существует, возвращает его, в противном случае возвращает false
:
function nextPermutation(array) {
var i = array.length - 1;
while (i > 0 && array[i - 1] >= array[i]) {
i--;
}
if (i <= 0) {
return false;
}
var j = array.length - 1;
while (array[j] <= array[i - 1]) {
j--;
}
var temp = array[i - 1];
array[i - 1] = array[j];
array[j] = temp;
j = array.length - 1;
while (i < j) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
return array;
}
Ответ 3
Домашнее задание? Во всяком случае, можно посмотреть на функцию С++ std:: next_permutation, или это:
http://blog.bjrn.se/2008/04/lexicographic-permutations-using.html
Ответ 4
Используя источник, цитируемый @Fleischpfanzerl
Следующая лексикографическая перестановка
Мы выполняем следующие шаги, чтобы найти следующую лексикографическую перестановку:
nums = [0,1,2,5,3,3,0]
nums = [0]*5
curr = nums[-1]
pivot = -1
for items in nums[-2::-1]:
if items >= curr:
pivot -= 1
curr = items
else:
break
if pivot == - len(nums):
print('break') # The input is already the last possible permutation
j = len(nums) - 1
while nums[j] <= nums[pivot - 1]:
j -= 1
nums[j], nums[pivot - 1] = nums[pivot - 1], nums[j]
nums[pivot:] = nums[pivot:][::-1]
> [1, 3, 0, 2, 3, 5]
Идея такова: идея состоит в том, чтобы следовать шагам -
- Найдите индекс 'pivot' в конце массива так, чтобы nums [i - 1] <nums [i]
- Найдите индекс j такой, что nums [j]> nums [pivot - 1]
- Поменяйте местами оба этих индекса
- Обратный суффикс, начиная с точки разворота
Ответ 5
Мы можем найти следующую большую лексикографическую строку для данной строки S, используя следующий шаг.
1. Iterate over every character, we will get the last value i (starting from the first character) that satisfies the given condition S[i] < S[i + 1]
2. Now, we will get the last value j such that S[i] < S[j]
3. We now interchange S[i] and S[j]. And for every character from i+1 till the end, we sort the characters. i.e., sort(S[i+1]..S[len(S) - 1])
Данная строка является следующей самой большой лексикографической строкой S
. Также можно использовать вызов функции next_permutation
в С++.
Ответ 6
nextperm (a, n)
1. find an index j such that a[j….n - 1] forms a monotonically decreasing sequence.
2. If j == 0 next perm not possible
3. Else
1. Reverse the array a[j…n - 1]
2. Binary search for index of a[j - 1] in a[j….n - 1]
3. Let i be the returned index
4. Increment i until a[j - 1] < a[i]
5. Swap a[j - 1] and a[i]
O(n) for each permutation.
Ответ 7
void Solution::nextPermutation(vector<int> &a) {
int i,j=-1,k,t=a.size();
for(i=0;i<t-1;i++)
{
if(a[i]<a[i+1])
j=i;
}
if(j==-1)
reverse(a.begin(),a.end());
else
{
for(i=j+1;i<t;i++)
{
if(a[j]<a[i])
k=i;
}
swap(a[j],a[k]);
reverse(a.begin()+j+1,a.end());
}
}
Ответ 8
Отличное решение, которое работает, описано здесь: https://www.nayuki.io/page/next-lexicographic-permutation-algorithm. и если вы ищете
исходный код:
/**
* method to find the next lexicographical greater string
*
* @param w
* @return a new string
*/
static String biggerIsGreater(String w) {
char charArray[] = w.toCharArray();
int n = charArray.length;
int endIndex = 0;
// step-1) Start from the right most character and find the first character
// that is smaller than previous character.
for (endIndex = n - 1; endIndex > 0; endIndex--) {
if (charArray[endIndex] > charArray[endIndex - 1]) {
break;
}
}
// If no such char found, then all characters are in descending order
// means there cannot be a greater string with same set of characters
if (endIndex == 0) {
return "no answer";
} else {
int firstSmallChar = charArray[endIndex - 1], nextSmallChar = endIndex;
// step-2) Find the smallest character on right side of (endIndex - 1)'th
// character that is greater than charArray[endIndex - 1]
for (int startIndex = endIndex + 1; startIndex < n; startIndex++) {
if (charArray[startIndex] > firstSmallChar && charArray[startIndex] < charArray[nextSmallChar]) {
nextSmallChar = startIndex;
}
}
// step-3) Swap the above found next smallest character with charArray[endIndex - 1]
swap(charArray, endIndex - 1, nextSmallChar);
// step-4) Sort the charArray after (endIndex - 1)in ascending order
Arrays.sort(charArray, endIndex , n);
}
return new String(charArray);
}
/**
* method to swap ith character with jth character inside charArray
*
* @param charArray
* @param i
* @param j
*/
static void swap(char charArray[], int i, int j) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
Если вы ищете видео объяснение того же, вы можете посетить здесь.
Ответ 9
Я наткнулся на отличный учебник. ссылка: https://www.youtube.com/watch?v=quAS1iydq7U
void Solution::nextPermutation(vector<int> &a) {
int k=0;
int n=a.size();
for(int i=0;i<n-1;i++)
{
if(a[i]<a[i+1])
{
k=i;
}
}
int ele=INT_MAX;
int pos=0;
for(int i=k+1;i<n;i++)
{
if(a[i]>a[k] && a[i]<ele)
{
ele=a[i];pos=i;
}
}
if(pos!=0)
{
swap(a[k],a[pos]);
reverse(a.begin()+k+1,a.end());
}
}
Ответ 10
- Начните обход с конца списка. Сравните каждый с предыдущим значением индекса.
- Если предыдущее значение индекса (скажем, в индексе
i-1
), учитываяx
, ниже, чем текущее значение индекса (индексаi
), отсортируйте подсписок справа, начиная с текущей позицииi
. -
Выберите одно значение от текущей позиции до конца, которое чуть выше
x
, и поместите его в индексi-1
. В индексе значение было выбрано, поставитьx
. То есть:swap(list[i-1], list[j]) where j >= i, and the list is sorted from index "i" onwards
Код:
public void nextPermutation(ArrayList<Integer> a) {
for (int i = a.size()-1; i > 0; i--){
if (a.get(i) > a.get(i-1)){
Collections.sort(a.subList(i, a.size()));
for (int j = i; j < a.size(); j++){
if (a.get(j) > a.get(i-1)) {
int replaceWith = a.get(j); // Just higher than ith element at right side.
a.set(j, a.get(i-1));
a.set(i-1, replaceWith);
return;
}
}
}
}
// It means the values are already in non-increasing order. i.e. Lexicographical highest
// So reset it back to lowest possible order by making it non-decreasing order.
for (int i = 0, j = a.size()-1; i < j; i++, j--){
int tmp = a.get(i);
a.set(i, a.get(j));
a.set(j, tmp);
}
}
Пример:
10 40 30 20 => 20 10 30 40 // 20 is just bigger than 10
10 40 30 20 5 => 20 5 10 30 40 // 20 is just bigger than 10. Numbers on right side are just sorted form of this set {numberOnRightSide - justBigger + numberToBeReplaced}.
Ответ 11
Это достаточно эффективно до 11 строк.
// next_permutation example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void nextPerm(string word) {
vector<char> v(word.begin(), word.end());
vector<string> permvec; // permutation vector
string perm;
int counter = 0; //
int position = 0; // to find the position of keyword in the permutation vector
sort (v.begin(),v.end());
do {
perm = "";
for (vector<char>::const_iterator i = v.begin(); i != v.end(); ++i) {
perm += *i;
}
permvec.push_back(perm); // add permutation to vector
if (perm == word) {
position = counter +1;
}
counter++;
} while (next_permutation(v.begin(),v.end() ));
if (permvec.size() < 2 || word.length() < 2) {
cout << "No answer" << endl;
}
else if (position !=0) {
cout << "Answer: " << permvec.at(position) << endl;
}
}
int main () {
string word = "nextperm";
string key = "mreptxen";
nextPerm(word,key); // will check if the key is a permutation of the given word and return the next permutation after the key.
return 0;
}
Ответ 12
Я надеюсь, что этот код может быть полезен.
int main() {
char str[100];
cin>>str;
int len=strlen(len);
int f=next_permutation(str,str+len);
if(f>0) {
print the string
} else {
cout<<"no answer";
}
}