题解 | #四则运算#

24点运算

http://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d

使用递归,很好实现,很好理解

const d = { 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, J: 11, Q: 12, K: 13, A: 1, 2: 2 }
const res = []
function f(nums, target) {
  if (nums.length == 1) {
    if (d[nums[0]] == target) {
      res.push(nums[0])
      return true
    } else {
      return false
    }
  }
  for (let i = 0; i < nums.length; i++) {
    const a = nums[i]
    const b = nums.slice(0, i).concat(nums.slice(i + 1))
    if (f(b, target + d[a])) {
      res.push('-' + a)
      return true
    } else if (f(b, target - d[a])) {
      res.push('+' + a)
      return true
    } else if (f(b, target * d[a])) {
      res.push('/' + a)
      return true
    } else if (target % d[a] === 0 && f(b, target / d[a])) {
      res.push('*' + a)
      return true
    }
  }
  return false
}
function get24(str) {
  var nums = str.split(' ')
  if (nums.includes('joker') || nums.includes('JOKER')) {
    console.log('ERROR')
  } else {
    if (f(nums, 24)) {
      console.log(res.join(''))
    } else {
      console.log('NONE')
    }
  }
}
get24(readline())
全部评论
不理解第15行到第26行,+-*/为啥和res中的符号都是反着的,这个哪位大神帮忙解答下啊
点赞
送花
回复
分享
发布于 2022-07-07 16:12
除数是整除的时候是不是没有考虑啊
点赞
送花
回复
分享
发布于 2022-12-24 15:53 广西
滴滴
校招火热招聘中
官网直投

相关推荐

TP-LINK 前端工程师 年包大概20出头 本科
点赞 评论 收藏
转发
3 收藏 评论
分享
牛客网
牛客企业服务