要獲得所有解決方案,請爲號碼1:4
預留4個插槽(因爲每個號碼必須至少出現一次),並考慮所有可能的長度 - 4個序列1:4
以填充剩餘的插槽。排序和刪除重複項留下35個非遞減序列:
# The sequences will be the rows of a matrix. First, the 'reserved' slots:
reserved = matrix(1:4, 256, 4, byrow=TRUE)
# Add all combinations of 1:4 to fill the remaining four slots:
result = cbind(reserved,
unname(as.matrix(expand.grid(1:4, 1:4, 1:4, 1:4))))
# Now simply sort and de-duplicate along rows:
result = t(apply(result, 1, sort))
result = unique(result)
> head(result)
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
# [1,] 1 1 1 1 1 2 3 4
# [2,] 1 1 1 1 2 2 3 4
# [3,] 1 1 1 1 2 3 3 4
# [4,] 1 1 1 1 2 3 4 4
# [5,] 1 1 1 1 2 2 3 4
# [6,] 1 1 1 2 2 2 3 4
您到目前爲止嘗試了什麼?你有什麼想法嗎? – ventiseis
如果向量中的所有數字在1到4之間,'sort(vector)'將保證結果是一個解決方案。 – www