HyeLog
2309_일곱 난쟁이 본문
재귀함수를 사용해서 난쟁이 9명 중에서 7명을 선택하는 방식으로 풀었다.
답을 찾은 경우 바로 프로그램을 종료하기 위해 exit(0)을 이용했다.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int height[9];
vector<int> seven;
void solve(int idx, int cnt, int sum) {
if (cnt == 7) {
if (sum == 100) {
sort(seven.begin(), seven.end());
for (int i = 0; i < seven.size(); i++) {
cout << seven[i] << '\n';
}
exit(0);
}
else return;
}
for (int i = idx; i < 9; i++) {
seven.push_back(height[i]);
solve(idx + 1, cnt + 1, sum + height[i]);
seven.pop_back();
solve(idx + 1, cnt, sum);
}
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
for (int i = 0; i < 9; i++) {
cin >> height[i];
}
solve(0, 0, 0);
}
'알고리즘' 카테고리의 다른 글
14500_테트로미노 (2) | 2023.01.04 |
---|---|
1107_리모컨 (0) | 2023.01.04 |
1476_날짜 계산 (0) | 2022.12.23 |
3085_사탕게임 (0) | 2022.12.23 |
1978_소수 찾기 (0) | 2022.12.08 |