개발팁

c++ 순열 조합

은찐찐 2019. 2. 12. 15:27

순열 조합 참고 사이트

http://swlock.blogspot.com/2016/11/permutation-combination-algorithm-full.html


중복 순열

#include <stdio.h>

#define N 4
#define R 3

int selected[R];

void full(int depth)
{
  int i;
  if( R==depth){
    // 모두 선택 되었음 출력하기
    for(i=0;i<R;i++){
      printf("%d ",selected[i]);
    }
    printf("\n");
    return;
  }
  for(i=1;i<=N;i++){
    selected[depth]=i;
    full(depth+1);
  }
}

int main()
{
  full(0);
  return 0;
}


순열

#include <stdio.h> #define N 4 #define R 3 int selected[R]; int flag[N+1]; void full(int depth) { int i; if( R==depth){ // 모두 선택 되었음 출력하기 for(i=0;i<R;i++){ printf("%d ",selected[i]); } printf("\n"); return; } for(i=1;i<=N;i++){ if(flag[i]==1)continue; // 중복 없애는 부분 flag[i]=1; selected[depth]=i; full(depth+1); flag[i]=0; } } int main() { full(0); return 0; }