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.
6
1 3 5 6 7 10
Print “YES” or “NO” on the first line.
YES
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;
}