Finding Permutations

Problem

If N natural numbers less than or equal to 10 are given, M out of them are selected and all methods are printed out.

input

  • The first line is given the natural numbers N(3<=N<=10) and M(2<=M<=N)
  • In the second line, N natural numbers are given in ascending order
3 2

3 6 9

output

  • Prints the result on the first line. Prints the last total number of cases
  • The output order is alphabetically in ascending order
3 6
3 9
6 3
6 9
9 3
9 6
6

Solution

function solution(m, arr) {
	let answer = [];
	let temp = Array.from({ length: m }, () => 0);

	function DFS(L) {
		if (L === m) {
			if (temp[m - 1]) answer.push([...temp]);
		} else {
			for (let i = 0; i < arr.length; i++) {
				if (L && temp[L - 1] === arr[i]) temp[L] = 0;
				else temp[L] = arr[i];

				DFS(L + 1);
			}
		}
	}
	DFS(0);
	return answer;
}
function solution(m, arr) {
	let answer = [];
	n = arr.length;
	let ch = Array.from({ length: n }, () => 0); //check array
	let tmp = Array.from({ length: m }, () => 0);

	function DFS(L) {
		if (L === m) {
			answer.push(tmp.slice());
		} else {
			for (let i = 0; i < n; i++) {
				if (!ch[i]) {
					ch[i] = 1;
					tmp[L] = arr[i];
					DFS(L + 1);
					ch[i] = 0;
				}
			}
		}
	}
	DFS(0);
	return answer;
}