next_permutation(C++) - 순열&조합

김정욱·2021년 3월 4일
0

Algorithm - 내용(C++)

목록 보기
8/9
post-thumbnail

순열

  • 배열의 원소들에 대한 모든 순열 경우를 탐색할 수 있다.
  • do~while()문과 적절하게 어울린다.
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int arr[5] = {1,2,3,4,5};
    do{
        for(int i=0;i<5;i++)
            cout << arr[i] << ' ';
        cout <<'\n';
    }while(next_permutation(arr,arr+5));
    return 0;
}

  • 이런식으로 모든 경우의 수를 출력해준다!

조합

  • 같은 함수를 통해 조합도 구현할 수 있다.
  • 4개중 2개를 뽑는 경우의 수를 구하는 코드
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int arr[4] = {0, 0, 1, 1};
    do{
        for(int i=0;i<5;i++)
            if(arr[i] == 0)
                cout << i+1 << ' ';
        cout <<'\n';
    }while(next_permutation(arr,arr+4));
    return 0;
}

  • 0과 1을 사용해서 응용한 방법이다
    • 전채개수 = 뽑을 전채 개수
    • 0의개수 = 내가 뽑을 개수
profile
Developer & PhotoGrapher

0개의 댓글