Permutation : 순열 -> 순서가 존재
표기 : nPr
ex) 1,2,3이 있을 때 중복없이 나올 수 있는 순열의 수
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] -> 총 6가지
Combination : 조합 -> 순서가 없음
표기 : nCr
ex) 1,2,3이 있을 때 조합의 수
[1,2,3] -> 1가지
Input : nums = [1,2,3]
Output : [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
tempList 에 담기는 과정
-> 중복을 거르지 않았을 때
[],
[1],
[1, 1],
[1, 1, 1],
[1, 1, 2],
[1, 1, 3],
[1, 1],
[1],
[1,2],
[1,2,1],
[1,2,2],
[1,2,3],
[1,2],
[1],
...
경우의 수
-> 진한 부분이 최종적으로 뽑아야 하는 부분
[1, 1, 1], [1, 1, 2], [1, 1, 3],
[1, 2, 1], [1, 2, 2], [1, 2, 3],
[1, 3, 1], [1, 3, 2], [1, 3, 3],
[2, 1, 1], [2, 1, 2], [2, 1, 3],
[2, 2, 1], [2, 2, 2], [2, 2, 3],
[2, 3, 1], [2, 3, 2], [2, 3, 3],
[3, 1, 1], [3, 1, 2], [3, 1, 3],
[3, 2, 1], [3, 2, 2], [3, 2, 3],
[3, 3, 1], [3, 3, 2], [3, 3, 3]
import java.util.*;
public class Q1 {
public static void main(String[] args) {
int[] nums = { 1, 2, 3 };
System.out.println(solve(nums));
}
public static List<List<Integer>> solve(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> tempList = new ArrayList<Integer>();
backtracking(result, tempList, nums);
return result;
}
public static void backtracking(List<List<Integer>> result, List<Integer> tempList, int[] nums) {
if (tempList.size() == nums.length) {
result.add(new ArrayList<>(tempList));
} else {
for (int i = 0; i < nums.length; i++) {
if (tempList.contains(nums[i])) {
continue;
}
tempList.add(nums[i]);
backtracking(result, tempList, nums);
tempList.remove(tempList.size() - 1);
}
}
}
}
N이 주어졌을 때 1~N까지의 수를 이용하여 k개 만큼의 조합을 구해라.
Input: n = 3, k = 2
Output: [[1, 2], [1, 3], [2, 3]]
import java.util.*;
public class Q2 {
public static void main(String[] args) {
int n = 3, k = 2;
System.out.println(solve(n, k));
}
public static List<List<Integer>> solve(int n, int k) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> tempList = new ArrayList<Integer>();
backtraking(result, tempList, n, k, 1);
return result;
}
public static void backtraking(List<List<Integer>> result, List<Integer> tempList, int n, int k, int start) {
if (tempList.size() == k) {
result.add(new ArrayList<>(tempList));
} else if (tempList.size() > k) {
return;
}
for (int i = start; i <= n; i++) {
tempList.add(i);
backtraking(result, tempList, n, k, i + 1);
tempList.remove(tempList.size() - 1);
}
}
}
인프런 강의 : 코딩테스트 전 꼭 알아야 할 개념과 문제(with 자바) - 푸샵맨 코딩스터디