Matrix of constrained sums using R
Instead of a top-down (very memory intensive) approach, I would recommend a somewhat bottom-up approach, where you add one column at a time then do the reductions, add another column, etc. Try this:

expand.mat &lt;- function(mat, vec) {
   out &lt;- matrix(0L, nrow = nrow(mat) * length(vec),
                     ncol = ncol(mat) + 1)
   for (i in 1:ncol(mat)) out[, i] &lt;- mat[, i]
   out[, ncol(mat) + 1] &lt;- rep(vec, each = nrow(mat))
   return(out)
}

valid.counts3 &lt;- function(x, cvec) {
   l   &lt;-  length(cvec) + 1
   vec &lt;- seq(from = 0, to = cvec[1])
   mat &lt;- matrix(vec, ncol = 1)

   for (j in 2:l) {

      mat  &lt;- expand.mat(mat, vec)
      rsum &lt;- rowSums(mat)
      mat  &lt;- mat[rsum &lt;= x &amp; rsum + cvec[1] * (l - j) &gt;= x, ]

      for (i in 1:(j-1)) {
         k &lt;- j - i + 1
         if (k == l) next
         rsum &lt;- rowSums(mat[, i:j])
         mat  &lt;- mat[rsum &lt;= cvec[k], ]
      }
   }

   return(mat)
}

system.time({
   res &lt;- valid.counts3(x = 148, cvec = c(36, 67, 92, 119))
})
#    user  system elapsed 
#   0.279   0.036   0.319


Edit: And to handle a vector of x as input, make these slight changes. It will return a list of matrices.

valid.counts3 &lt;- function(x, cvec) {
   l   &lt;-  length(cvec) + 1
   vec &lt;- seq(from = 0, to = cvec[1])
   mat &lt;- matrix(vec, ncol = 1)

   for (j in 2:l) {

      mat  &lt;- expand.mat(mat, vec)
      rsum &lt;- rowSums(mat)
      mat  &lt;- mat[rsum &lt;= max(x) &amp; rsum + cvec[1] * (l - j) &gt;= min(x), ]

      for (i in 1:(j-1)) {
         k &lt;- j - i + 1
         if (k == l) next
         rsum &lt;- rowSums(mat[, i:j])
         mat  &lt;- mat[rsum &lt;= cvec[k], ]
      }
   }

   mat &lt;- mat[rowSums(mat) %in% x, ]
   idx &lt;- split(seq(nrow(mat)), rowSums(mat))
   return(lapply(idx, function(i, x) x[i, ], mat))
}

system.time({
   res &lt;- valid.counts3(x = seq(from = 148, to = 155), cvec = c(36, 67, 92, 119))
})
#    user  system elapsed 
#   0.333   0.048   0.381 

sapply(res, nrow)
#  148  149  150  151  152  153  154  155 
# 8649 5776 3600 2025 1024  441  144   25