SMALL

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

 

15651번: N과 M (3)

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

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, 1);
            Console.WriteLine(sb.ToString());
        }
        static void dfs(int N, int M, int cnt, int num)
        {
            if (cnt == M)
            {
                for(int i=0;i<M;i++)
                {
                    sb.Append(result[i]+" ");
                }
                sb.AppendLine();
                return;
            }
            for(int i=num;i<=N;i++)
            {
                //if (!visited[i])
                //{
                //    visited[i]=true;
                    result[cnt] = i;
                    dfs(N, M, cnt+1, num);
                //    visited[i] = false;
                //}
            }
        }
    }
}

  • 후기

시간이 2272ms인데 더 줄일 수 없을까...?

LIST

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

[C#]백준 23292번: 코딩 바이오리듬  (0) 2023.07.19
[C#]백준 15652번: N과 M(4)  (0) 2023.07.19
[C#]백준 15650번: N과 M(2)  (0) 2023.07.19
[C#]백준 15649번: N과 M(1)  (0) 2023.07.19
[C#]백준 1541번: 잃어버린 괄호  (0) 2023.07.19

+ Recent posts