I am trying to practice LeetCode problems for Data Scientist interviews in R
and One of the question I came across is foursum. To solve this, I am trying to generate all the different four combinations and calculating the sum using apply
function. Is there a better way to optimize it in R
without using 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