【问题标题】:all possible combinations to divide pack of candies所有可能的组合来划分糖果包
【发布时间】:2020-08-08 01:23:08
【问题描述】:

我有问题要解决,我被卡住了,我不知道如何开始。

假设我有 R 个孩子和 S 个糖果。我想在孩子之间分配糖果。每个孩子可以获得 0、1、2、3 或 4 个糖果。如何找到这种划分的所有可能性?

#include <iostream>
using namespace std;

void solve(int r, int s) {
    if (s == 0)
    {
        cout << "no more candies" << endl;
        return;
    }
    
    if (r == 0)
    {
        cout << "last child" << endl;
        return;
    }

    for (int j = 0; j < 4 && j <= s; ++j)
    {
        cout << "r: " << r  << " j: " << j << endl;

        solve(r-1, s - j);
    }
}

int main () {
    int r, s;
    cin >> r >> s;
    solve(r, s);
    return 0;
}

现在我有这样的东西,我在输出中看到我在这里有解决方案,但我不知道如何抓取所有可能性并将其存储到例如向量中。

【问题讨论】:

  • 你应该首先编写程序来读取输入。

标签: c++ algorithm combinations


【解决方案1】:

只存储计数并在最后一个递归级别保存变体

vector<int> counts;
vector<vector<int>> sol;

void solve(int r, int s) {
    if (s == 0)
    {
        sol.push_back(counts);
        return;
    }

    if (r == 0)
    {
        return;
    }

    for (int j = 0; j <= 4 && j <= s; ++j)
    {
        counts[r - 1] += j;
        solve(r - 1, s - j);
        counts[r - 1] -= j;
    }
}

int main() {
    int r, s;
    r = 3;
    s = 5;
    for (int j = 0; j < r; ++j)
        counts.push_back(0);
    solve(r, s);
    for (int i = 0; i < sol.size(); i++) {
        for (int j = 0; j < sol[i].size(); j++) {
            cout << sol[i][j] << ' ';
        }
        cout << endl;
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 2017-06-04
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 2021-08-23
    • 2015-10-22
    • 1970-01-01
    相关资源
    最近更新 更多