Exercise 07 digital algorithm combined sum

topic

No repeating a given array of numbers arrthat specifies the number of nobject is given, and sumdetermines whether it contains the ndifferent numbers obtained by adding sumthe 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 sumare equal, if returns are equal true, if not equal to continue the walk until the end of the traverse, returnfalse

Recursive condition is arrand nand sumat the same time changes, so that every time ndwindling, 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;
}

Guess you like

Origin blog.csdn.net/duola8789/article/details/93378292