【问题标题】:generate all possible combinations of n bit binary numbers wherein k bits are always set using backtracking only生成 n 位二进制数的所有可能组合,其中 k 位始终仅使用回溯设置
【发布时间】:2017-04-01 20:05:37
【问题描述】:

在回溯时陷入如何设置位的问题。无法在输出中排除 001,010 和 100。提供一个算法会很有帮助。

Eg:n=3,k=2,arr={0,0,0},index=0

void printwithKbitset(int n,int k,int arr[],int index)
{
   if(k==0)
    {
        for(int i=0;i<3;i++)
            cout<<arr[i];
        cout<<"\n";
   return; 
   }
    if(n>1)
        printwithKbitset(n-1,k,arr,index+1);
   if(k>0)
   {
   arr[index]=1;
   printwithKbitset(n,k-1,arr,index);
 arr[index]=0;  
    }

Output:   
001
011
010
101
110
100

【问题讨论】:

  • “提供一个算法会很有帮助。”是的,它会,但算法是什么?目标是什么?
  • 练习用
  • @user4581301 在没有帮助的情况下实现了目标,不,谢谢。

标签: c++ algorithm combinations backtracking


【解决方案1】:

要走的路是使用std::next_permutation:

#include <algorithm>
#include <iostream>
#include <vector>

void print(const std::vector<int>& v)
{
    for (auto e : v) {
        std::cout << e << " ";   
    }
    std::cout << std::endl;
}

int main()
{
    std::vector<int> v {0, 1, 1};

    do {
        print(v);
    } while (std::next_permutation(std::begin(v), std::end(v)));
}

Demo

【讨论】:

  • 不使用STL可以实现吗?此外,代码似乎没有使用回溯
  • 如果你想知道它是如何实现的,你可以看看std::next_permutation的实现。可以重写。
猜你喜欢
  • 2010-12-23
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 2012-03-22
相关资源
最近更新 更多