본문 바로가기
중요한건 꾸준함!/자료구조, 알고리즘

순열(15649), 조합(15650) (c++)

by 방배킹 2023. 4. 28.

순열 구현 문제

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

 

15649번: N과 M (1)

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해

www.acmicpc.net

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int n, m;

int arr[9] = {};
bool visited[9] = {};

void dfs(int depth) {
	if (depth == m) {
		for (int i = 0; i < m; i++) {
			cout << arr[i] << " ";
		}
		cout << "\n";
		return;
	}
	for (int i = 1; i <= n; i++) {
		if (!visited[i]) {
			visited[i] = true;
			arr[depth] = i;
			dfs(depth + 1);
			visited[i] = false;
		}
	}
}
int main() {

	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);

	cin >> n >> m;
	dfs(0);

	return 0;
}

조합 구현 문제

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

 

15650번: N과 M (2)

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해

www.acmicpc.net

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int n, m;

int arr[9] = {};
bool visited[9] = {};

void dfs(int depth, int num) {
	if (depth == m) {
		for (int i = 0; i < m; i++) {
			cout << arr[i] << " ";
		}
		cout << "\n";
		return;
	}
	for (int i = num; i <= n; i++) {
		if (!visited[i]) {
			visited[i] = true;
			arr[depth] = i;
			dfs(depth + 1,i+1);
			visited[i] = false;
		}
	}
}
int main() {

	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);

	cin >> n >> m;
	dfs(0,1);

	return 0;

}

'중요한건 꾸준함! > 자료구조, 알고리즘' 카테고리의 다른 글

[BOJ] 백준 6443 애너그램 (Java)  (1) 2024.12.12
[C++ STL] next_permutaion  (0) 2024.04.16
[c++ STL]vector sort() 함수와 compare 함수  (0) 2023.04.11
트리  (0) 2023.04.03
이분 그래프  (0) 2023.03.27

댓글