Front-end interview brushing day9 (updated daily high-frequency inspection points for front-end interviews)

Codewords are not easy, and helpful students hope to pay attention to my WeChat public account: Code program life, thank you! The code is self-used and fetched.

Insert picture description here

Provides a topic that is common in front-end interviews every day. And I have established a QQ group ( 425554900 ), which provides a large number of interview questions and answers, including questions and answers updated daily by CSDN. Welcome everyone to join the group to communicate, check in, and make progress together.

Today's topic:

Please use the algorithm to achieve, from the given unordered, non-repetitive array data, take out n numbers, and make the sum of them sum. And give the time/space complexity of the algorithm. (There is no need to find all the solutions, just find one)


answer:

/**
* 
* 解题思路:从array中取出n个数全排列,在取的同时判断是否符合条件,为了不影响后续排列,每次递归完成,将当前的数组添加到正在排序的array中
* 时间复杂度O(n)
* 空间复杂度O(n)
* @param {Array} array 需要判断的数组
* @param {number} n 取出n个数
* @param {number} sum 和为sum的值
* @param {array} temp 输出和为sum的数组 
*/

function getAllCombin(array, n, sum, temp) {
    
    
  if (temp.length === n) {
    
    
    if (temp.reduce((t, c) => t + c) === sum) {
    
    
      return temp;
    }
    return false;
  }
  for (let i = 0; i < array.length; i++) {
    
    
    const current = array.shift();
    temp.push(current);
    const result = getAllCombin(array, n, sum, temp);
    if (result) {
    
    
      return result;
    }
    temp.pop();
    array.push(current);
  }
}

const arr = [1, 5, 6, 2, 4, 3];
console.log(getAllCombin(arr, 3, 10, []));

I will help you organize each day's questions and super detailed answers. Welcome to join the group to receive the answers to the questions of the day and the answers to the previous questions.


After paying attention to the official account , reply [ front-end interview questions ] and receive a large number of front-end interview questions summary pdf data

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46171043/article/details/115112758