[C++ 코딩 TIP] next_permutation

Seunghyeon·2023년 4월 8일

C++ 알고리즘 TIP

목록 보기
1/2

설명

간단하게 설명하자면

  1. 가능한 모든 순열 구하기

  2. 조합 구하기 ex) 4 C 2



next_permutation은 fill 함수처럼 배열의 처음과 끝을 인자로 받는다.

한번 실행 후, 그 다음 순열이 있을 경우 true를 반환하고
그렇지 않을 경우 false를 반환하여 종료한다

그래서 일반적으로 do while문으로 사용함.

함수에 들어가는 배열이 오름차순이어야 작동함

  1. 순열 구하는 방식으로 사용했을 때 (get_permutation)

  2. 조합 구하는 방식으로 사용했을 때 (combination)

둘의 사용법은 살짝 다르므로 코드를 보고 그 차이를 이해하기 바람.


코드

#include <bits/stdc++.h>
using namespace std;

int n;
int arr[4] = { 0, 0, 1, 1 };
int temp[4] = { 1, 2, 3, 4 };

// 가능한 순열을 모두 구할 때 사용하는 next_permutation
void get_permutation()
{
	do {
		for (int i = 0; i < 4; i++)
		{
			cout << temp[i] << " ";
		}
		cout << endl;
	} while (next_permutation(temp, temp + 4));
}

// 4개중 2개를 고를때 사용하기도 함. 4 C 2
void combination()
{
	do {
		for (int i = 0; i < 4; i++)
		{
			if (arr[i] == 0)
				cout << temp[i] << " ";
		}

		cout << endl;
	} while (next_permutation(arr, arr + 4));
}


int main(void)
{
	get_permutation();
	//combination();

	return 0;
}
profile
그냥 합니다.

0개의 댓글