백준 문제풀이/실버1

백준 1821번 - 수들의 합 6 (조합 next_permutation)

void_melody 2022. 8. 4. 13:50

https://www.acmicpc.net/problem/1821

 

1821번: 수들의 합 6

첫째 줄에 두개의 정수 N(1 ≤ N ≤ 10)과 F가 주어진다. N은 가장 윗줄에 있는 숫자의 개수를 의미하며 F는 가장 밑에 줄에 있는 수로 1,000,000 이하인 자연수이다.

www.acmicpc.net

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

int main()
{
	int n, f;
	cin >> n >> f;

	vector<int> v;
	for (int i = 1; i <= n; i++)
		v.push_back(i);
	do 
	{
		int arr[10][10];
		int index = 0;
		for (auto i = v.begin(); i != v.end(); i++)
		{
			arr[0][index] = *i;
			index++;
		}
		for (int j = 1; j < n; j++)
		{
			for (int i = 0; i < n - j; i++)
			{
				arr[j][i] = arr[j - 1][i] + arr[j - 1][i + 1];
			}
		}
		if (arr[n - 1][0] == f)
		{
			for (int t = 0; t < n; t++)
			{
				cout << arr[0][t] << ' ';
			}
			break;
		}
	} while (next_permutation(v.begin(), v.end()));

	
	return 0;
}

조합들을 구하기 위해서 next_permutation 함수를 활용했다.

  • next_permutation : 현재 나와 있는 수열에서 인자로 넘어간 범위에 해당하는 다음 순열을 구하고
    true를 반환. 없으면 false 반환.
bool next_permutation(BidirectionalIterator first, BidirectionalIterator last);