>  기사  >  백엔드 개발  >  STL을 사용하여 주어진 문자열의 C++ 완전 순열 구현

STL을 사용하여 주어진 문자열의 C++ 완전 순열 구현

王林
王林앞으로
2023-09-01 23:33:06858검색

STL을 사용하여 주어진 문자열의 C++ 완전 순열 구현

주어진 문자열의 문자가 어떤 형태로든 재배열되면 문자열의 배열이 형성됩니다. 예를 들어, 이 튜토리얼에서는 C++의 표준 템플릿 라이브러리를 사용하여 주어진 문자열의 모든 순열을 인쇄하는 방법에 대해 설명합니다

Input : s = “ADT”

Output : “ADT”, “ATD”, “DAT”, “DTA”, “TAD”, “TDA”

Explanation : In the given output as you can see all the string are made up of same three character present in our string and are just rearranged thus they fit in the definition of a permutation of a string now there is one more thing to note these are all the permutations possible of string s.

주어진 문자열의 모든 순열을 인쇄하는 방법에는 두 가지가 있습니다

Rotate()

우리는 첫 번째로 사용되는 방법은 회전 방법을 사용하는 것입니다. 이 방법에서는 문자열을 회전시키는 데 사용되는 STL의 회전 기능을 사용하고 재귀를 사용하여 배열을 인쇄합니다.

Example

위 메서드에 대한 C++ 코드

#include<bits/stdc++.h>
using namespace std;
void permutations(string s, string ans){
    if(s.size() == 0) {
// when our string which needs to
//be rotated becomes empty then it means
//that our permutation is stored in ans
        cout << ans << "\n";
        return ;
    }
    for(int i = 0; i < s.size(); i++){
        permutations(s.substr(1), ans + s[0]);
        // we are adding the
        // first character in our ans
        // passing all elements from index 1 in our
        // rotate string for next function.
        rotate(s.begin(), s.begin()+1, s.end());
        //rotating such that our second element becomes first
    }
}
int main(){
    string s = "ADT"; // given string
    permutations(s, "");
    return 0;
}

Output

ADT
ATD
DTA
DAT
TAD
TDA

Next_Permutation

이제 STL의 또 다른 함수인 next_Permutation을 사용하겠습니다. 이름에서 알 수 있듯이 이 함수의 반환 값은 다음 순열입니다. 문자열이 존재합니까? 그렇지 않은 경우 false를 반환합니다.

아시다시피 이 함수는 다음 순열을 확인합니다. 따라서 가능한 모든 순열을 얻으려면 먼저 문자열을 사전순으로 정렬해야 합니다.

예제

위 방법에 대한 C++ 코드

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s = "ADT"; // given string
    sort(s.begin(), s.end()); // sorting the string
    do{
        cout << s << "\n"; // printing the permutations
    }while(next_permutation(s.begin(), s.end())); // till next_permutations returns false
    return 0;
}

Output

ADT
ATD
DAT
DTA
TAD
TDA

위 프로그램에서는 문자열을 정렬한 다음 next_permutation 함수의 도움으로 가능한 모든 순열을 인쇄합니다.

결론

이 튜토리얼에서는 C++에서 STL을 사용하여 주어진 문자열의 가능한 모든 순열을 인쇄했습니다. 또한 문제에 대한 C++ 프로그램과 몇 가지 기본 STL 기능 및 사용법을 배웠습니다. 이 튜토리얼이 도움이 되었기를 바랍니다.

위 내용은 STL을 사용하여 주어진 문자열의 C++ 완전 순열 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제