列出1 ... n之间k个整数的所有可能组合(n选择k)

Asa*_*f R 11 c# algorithm math combinatorics

出于特殊的原因,我决定寻找一种算法,该算法产生1 ... n之间k个整数的所有可能选择,其中k整数中的顺序无关紧要(n选择k thingy).

从完全相同的原因,这是没有理由的,我也用C#实现了它.我的问题是:

你在我的算法或代码中看到任何错误吗?而且,更重要的是,你能建议一个更好的算法吗?

请注意算法而不是代码本身.这不是我写过的最漂亮的代码,虽然可以告诉你是否看到了错误.

编辑: Alogirthm解释 -

  • 我们持有k指数.
  • 这会创建k个嵌套for循环,其中循环i的索引是indices [i].
  • 它模拟k for for循环,其中indices [i + 1]属于嵌套在indices [i]循环中的循环.
  • indices [i]从索引[i-1] + 1到n-k + i + 1运行.

码:

public class AllPossibleCombination
{
    int n, k;
    int[] indices;
    List<int[]> combinations = null;

    public AllPossibleCombination(int n_, int k_)
    {
        if (n_ <= 0)
        {
            throw new ArgumentException("n_ must be in N+");
        }
        if (k_ <= 0)
        {
            throw new ArgumentException("k_ must be in N+");
        }
        if (k_ > n_)
        {
            throw new ArgumentException("k_ can be at most n_");
        }

        n = n_;
        k = k_;
        indices = new int[k];
        indices[0] = 1;
    }

    /// <summary>
    /// Returns all possible k combination of 0..n-1
    /// </summary>
    /// <returns></returns>
    public List<int[]> GetCombinations()
    {
        if (combinations == null)
        {
            combinations = new List<int[]>();
            Iterate(0);
        }
        return combinations;
    }

    private void Iterate(int ii)
    {
        //
        // Initialize
        //
        if (ii > 0)
        {
            indices[ii] = indices[ii - 1] + 1;
        }

        for (; indices[ii] <= (n - k + ii + 1); indices[ii]++)
        {
            if (ii < k - 1)
            {
                Iterate(ii + 1);
            }
            else
            {
                int[] combination = new int[k];
                indices.CopyTo(combination, 0);
                combinations.Add(combination);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我为长期问题道歉,它可能适合博客文章,但我确实想要社区的意见.

谢谢,
阿萨夫

小智 9

在C++中给出以下例程:

template <typename Iterator>
inline bool next_combination(const Iterator first, Iterator k, const Iterator last)
{
   /* Credits: Thomas Draper */
   if ((first == last) || (first == k) || (last == k))
      return false;
   Iterator itr1 = first;
   Iterator itr2 = last;
   ++itr1;
   if (last == itr1)
      return false;
   itr1 = last;
   --itr1;
   itr1 = k;
   --itr2;
   while (first != itr1)
   {
      if (*--itr1 < *itr2)
      {
         Iterator j = k;
         while (!(*itr1 < *j)) ++j;
         std::iter_swap(itr1,j);
         ++itr1;
         ++j;
         itr2 = k;
         std::rotate(itr1,j,last);
         while (last != j)
         {
            ++j;
            ++itr2;
         }
         std::rotate(k,itr2,last);
         return true;
      }
   }
   std::rotate(first,k,last);
   return false;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以继续执行以下操作:

std::string s = "123456789";
std::size_t k = 3;
do
{
   std::cout << std::string(s.begin(),s.begin() + k) << std::endl;
}
while(next_combination(s.begin(),s.begin() + k,s.end()));
Run Code Online (Sandbox Code Playgroud)


str*_*ger -1

这是我不久前用 C 编写的一个相对简单/高效的 nCr 程序:

main(n,k){float t=0,r=1;for(scanf("%d, %d",&n,&k);t++<k;r*=(1+n-t)/t);printf("%.0f\n",r);}
Run Code Online (Sandbox Code Playgroud)

好吧...可读版本。=] (不确定这是否与上面的1:1对应。)

void nCr(int n, int k) {
    float curK = 0, r = 1;
    while(curK < k) {
        ++curK;
        printf("%.0f\n", r);
        r *= (1 + n - curK) / curK;
    }
}
Run Code Online (Sandbox Code Playgroud)

yield您可以将其他内容(我不知道 C#)添加到您的列表中,而不是打印。