본문 바로가기

Beakjoon/backtracking

[백준] 15652번 N과 M (4) (C++) - backtracking

문제

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

 

15652번: N과 M (4)

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

www.acmicpc.net

코드

#include <iostream>

using namespace std;

int n, m;
int arr[9];

void dfs(int num, int cnt){
  if(cnt==m){
    for(int i=0; i<m; i++){
      cout << arr[i] << ' ';
    }
    cout <<'\n';
    return;
  }
  for(int i=num; i<=n; i++){
    arr[cnt] = i;
    dfs(i, cnt+1);
  }
}

int main(){
  cin >> n >> m;
  dfs(1, 0);
  return 0;
}

정리

이 문제와 15649번의 차이점은 (1)중복이 허용되고 (2)비내림차순인 수열이 출력되어야 된다는 것이다. 15650번과 15651번의 해결방법을 같이 적용하여 풀 수 있는 문제이다.

참조

https://kdongree.tistory.com/80

https://kdongree.tistory.com/81

https://kdongree.tistory.com/82