在B篮子中查找A苹果的所有分布

时间:2010-12-26 00:04:58

标签: algorithm optimization recursion combinatorics combinations

我们有一个苹果,B篮子。

您如何编写列出篮子的每个可能分布的算法。 一个篮子可以包含零或最大苹果。

例如:A = 6,B = 4(6个苹果,4个篮子)。

d1 = 6 0 0 0

d2 = 5 1 0 0

d3 = 5 0 1 0

d4 = 4 2 0 0

d5 = 3 0 0 3

.......

...... 等等......

4 个答案:

答案 0 :(得分:0)

您可以通过向当前存储桶添加0到apples_left苹果来递归生成它们,并返回当前存储桶的所有解决方案+剩余存储桶apples_left减去此存储桶的苹果。我认为代码在这里解释得最好,所以这里有一些Python代码:

def allocations(apples, baskets):
  if baskets == 0:
    if apples == 0:
      yield []
    return
  for a in xrange(apples+1):
    for alloc in allocations(apples-a, baskets-1):
      yield [a] + alloc

for i, alloc in enumerate(allocations(6, 4)):
  print 'd%d = %s' % (i+1, ' '.join(map(str, alloc)))

输出

d1 = 0 0 0 6
d2 = 0 0 1 5
d3 = 0 0 2 4
d4 = 0 0 3 3
...
d83 = 5 1 0 0
d84 = 6 0 0 0

Full output

答案 1 :(得分:0)

int basket[6];
void walk(int iBasket, int nRemain){
  if (iBasket == 6-1){
    basket[iBasket] = nRemain;
    // print baskets
  }
  else {
    for (i = 0; i <= nRemain; i++){
      basket[iBasket] = i;
      walk(iBasket+1, nRemain - i);
    }
  }
}

void main(){
  walk(0, 6);
}

答案 2 :(得分:0)

int apples;
int baskets;
cin >> apples >> baskets;
vector<int>(apples + baskets - 1, 0);
for(int i = baskets - 1; i < apples + baskets - 1; ++i)
 v[i] = 1;
do
{
 //first basket untill 1st 0
 //second basket from 1st to 2nd 0
 //third basket from 2nd to 3th 0
 //...
 //last basket from (basket - 1)th 0 to the end of vector
}next_permutation(v.begin(), v.end());

答案 3 :(得分:0)

如果您需要优化版本,您还可以使用算法生成组合,这些组合由Python的itertools等库提供。 请参阅我对此this question

的回答

from itertools import combinations, tee 


def diffed_tuple(t):
    t2, t1 = tee(t)
    for x in t2:
        break
    return tuple(e2 - e1 for e2, e1 in zip(t2, t1))



# --The Algorithm--
def compositions(n, k):
    for t in combinations(range(n+k), k+1):
        yield tuple(e-1 for e in diffed_tuple(t))