SMALL

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

 

15649번: N과 M (1)

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

www.acmicpc.net


  • 문제


  • 문제풀이

백트래킹 문제이다. 깊이 탐색을 활용해서 풀어준다.


  • 코드 1
using System.ComponentModel.Design;
using System.Text;

namespace ConsoleApp2
{
    internal class Program
    {
        static public StringBuilder sb = new StringBuilder();
        static public bool[] visited;
        static public int[] result;
        static void Main(string[] args)
        {
            
            
            string[] input = Console.ReadLine().Split();
            int N = int.Parse(input[0]);
            int M = int.Parse(input[1]);
            result= new int[N];
            visited= new bool[N];
            
            
            dfs(N, M, 0);
            Console.WriteLine(sb.ToString());
        }
        static void dfs(int N, int M, int cnt)
        {
            if (cnt == M)
            {
                for(int i=0;i<M;i++)
                {
                    sb.Append(result[i]+" ");
                }
                sb.AppendLine();
                
            }
            for(int i=0;i<N;i++)
            {
                if (!visited[i])
                {
                    visited[i]=true;
                    result[cnt] = i + 1;
                    dfs(N, M, cnt+1);
                    visited[i] = false;
                }
            }
        }
    }
}

  • 후기

DFS를 활용한 백트래킹 문제이다.

LIST

'백준 > C#' 카테고리의 다른 글

[C#]백준 15651번: N과 M(3)  (0) 2023.07.19
[C#]백준 15650번: N과 M(2)  (0) 2023.07.19
[C#]백준 1541번: 잃어버린 괄호  (0) 2023.07.19
[C#]백준 11047번: 동전 0  (0) 2023.07.19
[C#]백준 13305번: 주유소  (0) 2023.07.19

+ Recent posts