簡體   English   中英

Next_Permutation算法

[英]Next_Permutation algorithm

我正在嘗試編寫一種算法,以獲取給定整數數組的下一個排列。 我當前的代碼僅適用於一些輸入。 因此,我需要幫助找出問題出在哪里。

預期的輸出僅與最后三個元素的輸入不同。 因此,我檢查了后三個元素的算法實現。

void Solution::nextPermutation(vector<int> &A) {
    int j, i;
    for (i = A.size() - 1; i > 0; i--) {
        // loop to find i such that A[i-1] < A[i];

        if (A[i - 1] < A[i]) {
            j = i;
            break;
        }
    }

    if (i == 0)
        sort(A.begin(), A.end());
    // to give the lowest order if next_permutation is not possible

    if (i > 0) {
        // if next permutation is possible

        // to swap last element and element at j-1 th index

        if (j == A.size() - 1)
            swap(A[j-1], A[A.size() - 1]);
        else {
            for(int k = A.size() - 1; k >= j; k--) {
                if (A[k] > A[j-1]) {
                    swap(A[k], A[j- 1]);
                    break;
                }
            }
        }

        //to sort the elements after j-1 th index
        sort(A.begin()+j,A.end());
    }

輸入:

[444,994,701,319,695,52]

預期產量:

[444,994,701,695,52,319]

實際輸出:

[444,994,701,52,319,695]

如果要在j-1之后對向量進行排序,則不需要交換。

// Example program
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;

void nextPermutation(vector<int> &A) {
    int j,i;
    for(i=A.size()-1;i>0;i--){//loop to find i such that A[i-1]<A[i];
        if(A[i-1]<A[i]){j=i;break;}
    }
    if(i==0){sort(A.begin(),A.end());}
     /*to give the lowest order if  next_permutation 
    is not possible*/


    if(i>0){
        //if next permutation is possible
        //to swap last element and element at j-1 th index
        // swap(A[j-1],A[A.size()-1]);
        //to sort the elements after j-1 th index
        std::sort(A.begin()+j,A.end());
    }
}

int main()
{
    std::vector<int> v= {444, 994,701, 319, 695, 52};
    nextPermutation(v);
    for (int i = 0; i< v.size(); i++) {
        std:: cout << v[i] << "\n";
    }
}

另一個建議 :您可以完全避免排序。 在[j + 1,...,n]中找到k,使v [k]是最小元素> v [j],然后將向量v [j ... k-1]順時針旋轉一個單位(第一個元素轉到末尾)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM