topic
No repeating a given array of numbers arr
that specifies the number of n
object is given, and sum
determines whether it contains the n
different numbers obtained by adding sum
the case of
analysis
39 questions and 40 LeetCode title and similar questions, I verify that the code is self, do not know if there are problems.
First "algorithm graphic" entry read, painted LeetCode, brush to come back to re-look at it.
My current thinking is that the baseline condition is that n === 1
, at this time of the return condition is that the current cycle arr[i]
and sum
are equal, if returns are equal true
, if not equal to continue the walk until the end of the traverse, returnfalse
Recursive condition is arr
and n
and sum
at the same time changes, so that every time n
dwindling, downsizing
Code
function getSum(arr, n, sum) {
if (arr.length < n) {
return false
}
for (let i = 0; i < arr.length; i++) {
if (n === 1) {
if (arr[i] === sum) {
return true
}
} else {
const result = getSum(arr.slice(i + 1), n - 1, sum - arr[i]);
if (result) {
return true
}
}
}
return false;
}