[백준] N과 M (2) (java) 조합, Combination, 중복 X
    
      2020-03-27
    
    
  
  N과 M (2) (백준> Math / 조합, Combination, 중복 X)
문제설명
자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.
- 1부터 N까지 자연수 중에서 중복 없이 M개를 고른 수열
- 고른 수열은 오름차순이어야 한다.
예제
//입력
3 1
//출력
1
2
3
예제
//입력
4 2
//출력
1 2
1 3
1 4
2 3
2 4
3 4
풀이
package Math;
import java.util.*;
//조합 (중복 x)
public class beak_N과M_2 {
	static int n;
	static int m;
	static StringBuilder sb;
	static LinkedList<Integer> numbers;
	
	public static void comb(int count) {
		if(count == m) {
			for(int i: numbers)
				sb.append(i + " ");
			
			sb.append("\n");	
			return;
		}
		
		for(int i=0; i<n; i++) {
			if(numbers.contains(i+1))
				continue;
			
			if(!numbers.isEmpty() && i<numbers.getLast()) // i가 numbers의 맨 끝 값보다 작을때는 continue 
				continue;
			
			numbers.add(i+1);
			comb(count+1);
			numbers.removeLast();
		}
	}
	
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		n = sc.nextInt();
		m = sc.nextInt();
		
		sb = new StringBuilder();
		numbers = new LinkedList<>();
		
		comb(0);
		
		System.out.println(sb.toString());
	}
}
//https://limkydev.tistory.com/186  -> 순열, 중복순열, 조합, 중복조합
후기 (20min)
- 조합 - Combination
- 중복 X
- 1,2와 2,1를 같게, 하나로 취급한다
- 이건 배열로 풀어도 순서대로 나온다!