【问题标题】:String binary combinatorics字符串二进制组合
【发布时间】:2018-08-30 00:01:32
【问题描述】:

是否有一种简单的方法可以找到所有二进制字符串的数字加起来为 x 点的值,假设所有 1 都值 2 分,所有 0 都值 1 分。让我解释一下:

考虑到我收到一个数字 5,我怎样才能得到所有可能的字符串,例如 2*(个数)+ 1*zeros = 5。 5 下的所有结果:

00000

10000

0100

0010

0001

101

110

011

(我确实知道可能的解决方案的数量是 5+1 (x+1) 的斐波那契数,但我想不出找到所有值的方法)。

我正在考虑以二进制形式添加数字,或者可能使用基本转换器,但我可能在这里遗漏了一些东西。提前谢谢你。

【问题讨论】:

  • 只需找到所有二进制字符串并检查它们是否满足?还是使用递归?
  • 用必要的 0 和 1 生成字符串是微不足道的(在你的情况下是“00000”、“0001”和“011”),然后你可以使用std::next_permutation 来生成变体
  • 是的...有很多方法,选择一个你想要的。如果您仍然卡住,请回到这里。

标签: c++ string binary combinatorics


【解决方案1】:

通过单个循环,您可以生成基本字符串(在您的情况下为“00000”、“0001”和“011”),然后使用std::next_permutation()

for( int zeros = n; zeros >= 0; zeros -= 2 ) {
    int ones = ( n - zeros ) / 2;
    std::string base = std::string( zeros, '0' ) + std::string( ones, '1' );
}

live example

【讨论】:

  • ⁺1 这是一个非常简单和简洁的解决方案。 :)
  • @Jarod42 抱歉,我在这里修复了错误,但不是在 ideone 上,应该是 zeros >= 0,已更新
【解决方案2】:

试试这样:

#include <iostream>
#include <string>
#include <vector>

void getSums(int sum, std::vector<std::string>& results, std::string currSum) {
    if (0 == sum) {
        results.emplace_back(currSum.c_str());
        return;
    } else if (sum < 0) {
        return;
    } else {
        getSums(sum-2, results, currSum+"1");
        getSums(sum-1, results, currSum+"0");
    }
}

std::vector<std::string> getAllSums(int sum) {
    std::vector<std::string> results;
    std::string currSum;
    getSums(sum, results, currSum);
    return results;
}

int main() {
    std::vector<std::string> res = getAllSums(5);
    for (std::string& r : res) {
        std::cout << r << std::endl;
    }

}

或者切换到DP并缓存结果。

【讨论】:

    猜你喜欢
    • 2014-04-28
    • 2011-07-11
    • 1970-01-01
    • 2021-11-09
    • 2016-09-21
    • 1970-01-01
    • 2017-03-22
    • 2016-02-26
    • 2012-08-27
    相关资源
    最近更新 更多