본문 바로가기

알고리즘 문제풀이/알고리즘

[c++] 완전탐색(Brute-Force) / 순열 / next_permutation 함수

완전탐색(Brute-Force)

가능한 모든 경우의 수를 탐색하는 방법

 

순열

1) next_permutation() 사용

next_permutation - C++ Reference: http://www.cplusplus.com/reference/algorithm/next_permutation/

1. sort()로 정렬(오름차순)

2. do-while문조건 안에 next_permutation()

3. next_permutation의 parameter은 (첫번째 원소 주소, 마지막 원소 주소)

4. parameter로 넘긴 원소의 위치가 바뀌는 것, 이를 응용하여 쓸 것

// next_permutation example
#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort

using namespace std;

int main () {
  int myints[] = {1,2,3};

  sort (myints,myints+3);

  cout << "The 3! possible permutations with 3 elements:\n";
  do {
    cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( next_permutation(myints,myints+3) );

  cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}