Subsets with Equal Sum (DFS)

Problem

Given a set of natural numbers with N elements, When this set is divided into two subsets, if there is a case where the sum of the elements of the two subsets is equal, “YES” is output, Otherwise, write a program that prints “NO”.
The two subsets divisible by two are disjoint sets, and the sum of the two subsets should yield the original set given as input.
For example, if {1, 3, 5, 6, 7, 10} is entered, {1, 3, 5, 7} = {6, 10}. It can be seen that there is a case where the sum of the two subsets is equal to 16.

input

  • The first line is given a natural number N (1<=N<=10).
  • The second line gives N elements of the set. Each element is non-overlapping and its size is no more than 1,000,000.
6
1 3 5 6 7 10

output

Print “YES” or “NO” on the first line.

YES

Solution

function solution(arr) {
	let answer = 'NO',
		total = arr.reduce((a, b) => a + b, 0),
		n = arr.length,
		flag = 0;

	function DFS(L, sum) {
		if (flag) return;

		if (L >= n) {
			if (total - sum === sum) {
				answer = 'YES';
				flag = 1;
			}
		} else {
			DFS(L + 1, sum + arr[L]);
			DFS(L + 1, sum);
		}
	}
	DFS(0, 0);

	return answer;
}
function solution(arr) {
	let answer = 'NO',
		total = arr.reduce((a, b) => a + b, 0),
		n = arr.length;

	function DFS(L, sum) {
		if (L >= n) {
			if (total - sum === sum) {
				return (answer = 'YES');
			}
		} else {
			DFS(L + 1, sum + arr[L]);
			DFS(L + 1, sum);
		}
	}
	DFS(0, 0);

	return answer;
}