首页 > 解决方案 > 在 R 中计算 4 或 n 和

问题描述

我正在尝试为数据科学家面试练习 LeetCode 问题,R我遇到的问题之一是foursum。为了解决这个问题,我试图生成所有不同的四种组合并使用apply函数计算总和。有没有更好的方法来优化它R而不使用combn

GetFourSumCombinations <- function(TestVector,Target){
  CombinationPairs = combn(TestVector, 4)  ## Get all the combinations
  SumOfAllCombinations = apply(CombinationPairs, 2, sum)
  TargetElements = which(SumOfAllCombinations == Target)
  return(CombinationPairs[,TargetElements])
}
## OutPut:
TestVector = c(1, 0, -1, 0, -2, 2), Target = 0
GetFourSumCombinations(TestVector,0)
     [,1] [,2] [,3]
[1,]    1    1    0
[2,]    0   -1    0
[3,]   -1   -2   -2
[4,]    0    2    2

标签: r

解决方案


这是一个较短的版本

GetFourSumCombinations <- function(TestVector,Target){
   vals <- combn(TestVector, 4)
   vals[, colSums(vals) == Target]
}

GetFourSumCombinations(TestVector, Target)

#     [,1] [,2] [,3]
#[1,]    1    1    0
#[2,]    0   -1    0
#[3,]   -1   -2   -2
#[4,]    0    2    2

数据

TestVector <- c(1, 0, -1, 0, -2, 2)
Target = 0

推荐阅读