Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

请用算法实现,从给定的无序、不重复的数组data中,取出n个数,使其相加和为sum。并给出算法的时间/空间复杂度。(不需要找到所有的解,找到一个解即可) #902

Open
lgwebdream opened this issue Jul 6, 2020 · 4 comments
Labels
头条 company 算法 teach_tag

Comments

@lgwebdream
Copy link
Owner

No description provided.

@lgwebdream lgwebdream added 头条 company 算法 teach_tag labels Jul 6, 2020
@lgwebdream
Copy link
Owner Author

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

@jsm1003
Copy link

jsm1003 commented Jul 15, 2020

经典回溯法
function getAllCombin(array, n, sum) {
let res = null;

function isValid(item, track) {
return track.indexOf(item) === -1
}

function backtrack(nums, track, sum1) {
if(track.length === n && sum1 === sum) {
res = track.slice();
return;
}

for(let i = 0; i< nums.length; i++) {
  if(isValid(nums[i], track)) {
    track.push(nums[i])
    backtrack(nums, track, sum1 + nums[i])
    track.pop();
  }
}

}

backtrack(array, [], 0)
return res;
}

@GolderBrother
Copy link

function getResult(data, n, sum, temp = []) {
    if (temp.length === n) {
        const isExist = temp.reduce((accu, cur) => accu + cur, 0) === sum;
        if (isExist) return temp;
        return false;
    }
    let result = [];
    for (let i = 0, len = data.length; i < len; i++) {
        const current = data.shift();
        temp.push(current);
        result = getResult(data, n, sum, temp);
        if (result) break;
        // 还原为原数组
        temp.pop();
        data.push(current);
    }
    return result;
}
const arr = [1, 5, 6, 2, 4, 7, 3];
console.log(getResult(arr, 3, 10, []));

@GuoLizhi
Copy link

回溯算法

    // n数之和
    function nSum(arr = [], target, n) {
      const set = new Set()
      let result = null

      function backTack(currArr, currSum, currIndex) {
        // 回溯终止条件
        if (currSum === target && currArr.length === n) {
          result = [...currArr]
          return
        }
        for (let i = currIndex; i < arr.length; i++) {
          // 如果这个数之前已经使用过了,那直接跳过
          if (set.has(arr[i])) continue
          currArr.push(arr[i])
          set.add(arr[i])
          backTack(currArr, currSum + arr[i], currIndex + 1)
          // 回溯
          currArr.pop()
          set.delete(arr[i])
        }
        // 没有找到结果
        return null
      }

      backTack([], 0, 0)

      return result
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
头条 company 算法 teach_tag
Projects
None yet
Development

No branches or pull requests

4 participants