[6603] 로또

!·2022년 7월 19일
0

내 코드

#include <bits/stdc++.h>
using namespace std;
int field[15];
int arr[15];
int a;

void func(int k,int st)
{
    if(k==6)
    {
        for(int i =0;i<6;i++)
            cout << arr[i] << ' ';
        cout << '\n';
        return;
    }
    for(int i = st;i<a;i++)
    {
        arr[k] = field[i];
        func(k+1,i+1);
    }
}
int main(void)
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    while(1)
    {
        cin >> a;
        if(a==0) return 0;
        for(int i =0;i<a;i++)
            cin >> field[i];
        func(0,0);
        cout << '\n';
    }
    
}
  • 중복이 없이 한 호출에서 무조건 오른쪽에 있는 인덱스를 선택해야하기 때문에 방문배열을 선언할 필요 없다!

정답

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

int k, arr[15], mask[15];
int main(void) {
  ios::sync_with_stdio(0);
  cin.tie(0);

  while (1) {
    cin >> k;
    if (!k) break;

    for (int i = 0; i < k; i++)
      cin >> arr[i];
    for (int i = 6; i < k; i++)
      mask[i] = 1; // 뽑히지 않아야 할 원소를 표시
    do {
      for (int i = 0; i < k; i++) {
        if (!mask[i]) cout << arr[i] << " ";
      }
      cout << '\n';
    } while (next_permutation(mask, mask + k));
    cout << '\n';
  }
}

next_permutation() 을 이용한 풀이이다. mask 배열에 k-6 개수 만큼의 배열의 원소를 1로 만든다. (이 인덱스의 해당하는 값들은 출력되지 않는다.) 이후 mask 배열을 next_permutation 으로 do-while 문을 돌려 모든 가능한 k-6 개의 원소들이 선택될 수 있으며, 이 선택된 인덱스에 해당하는 값들은 출력되지 않는다....! 멋있는 풀이..

profile
개발자 지망생

0개의 댓글