假设我给出:

  1. 一个范围的整数 iRange (即从 1 起来 iRange)和
  2. 所需数量的组合

我想找到的所有数量的可能的组合,并打印出所有这些的组合。

例如:

给予: iRange = 5n = 3

然后组合的数量是 iRange! / ((iRange!-n!)*n!) = 5! / (5-3)! * 3! = 10 组合,并且输出为:

123 - 124 - 125 - 134 - 135 - 145 - 234 - 235 - 245 - 345

另一个例子:

给予: iRange = 4n = 2

然后组合的数量是 iRange! / ((iRange!-n!)*n!) = 4! / (4-2)! * 2! = 6 组合,并且输出为:

12 - 13 - 14 - 23 - 24 - 34

我尝试迄今为止是:

#include <iostream>
using namespace std;

int iRange= 0;
int iN=0;

int fact(int n)
{
    if ( n<1)
        return 1;
    else
    return fact(n-1)*n;
}

void print_combinations(int n, int iMxM)
{
    int iBigSetFact=fact(iMxM);
    int iDiffFact=fact(iMxM-n);
    int iSmallSetFact=fact(n);
    int iNoTotComb = (iBigSetFact/(iDiffFact*iSmallSetFact));
    cout<<"The number of possible combinations is: "<<iNoTotComb<<endl;
    cout<<" and these combinations are the following: "<<endl;


    int i, j, k;
    for (i = 0; i < iMxM - 1; i++)
    {
        for (j = i + 1; j < iMxM ; j++)
        {
            //for (k = j + 1; k < iMxM; k++)
                cout<<i+1<<j+1<<endl;
        }
    }
}

int main()
{
    cout<<"Please give the range (max) within which the combinations are to be found: "<<endl;
    cin>>iRange;
    cout<<"Please give the desired number of combinations: "<<endl; 
    cin>>iN;
    print_combinations(iN,iRange);
    return 0;   
}

我的问题: 我的代码相关的印刷的合作仅用于 n = 2, iRange = 4 我不能让它工作在一般情况下,即对任何 niRange.

有帮助吗?

解决方案

这是你的代码行编辑:D:D 递归 方案:

#include <iostream>

int iRange=0;   
int iN=0;           //Number of items taken from iRange, for which u want to print out the combinations
int iTotalCombs=0;
int* pTheRange;
int* pTempRange;

int find_factorial(int n)
{
    if ( n<1)
        return 1;
    else
    return find_factorial(n-1)*n;
}

//--->Here is another solution:
void print_out_combinations(int *P, int K, int n_i) 
{
    if (K == 0)
    {
        for (int j =iN;j>0;j--)
        std::cout<<P[j]<<" ";
        std::cout<<std::endl;
    }
    else
        for (int i = n_i; i < iRange; i++) 
        {
            P[K] = pTheRange[i];
            print_out_combinations(P, K-1, i+1);
        }
}
//Here ends the solution...

int main() 
{
    std::cout<<"Give the set of items -iRange- = ";
    std::cin>>iRange;
    std::cout<<"Give the items # -iN- of iRange for which the combinations will be created = ";
    std::cin>>iN;

    pTheRange = new int[iRange];
    for (int i = 0;i<iRange;i++)
    {
        pTheRange[i]=i+1;
    }
    pTempRange = new int[iN];

    iTotalCombs = (find_factorial(iRange)/(find_factorial(iRange-iN)*find_factorial(iN)));

    std::cout<<"The number of possible combinations is: "<<iTotalCombs<<std::endl;
    std::cout<<"i.e.the combinations of "<<iN<<" elements drawn from a set of size "<<iRange<<" are: "<<std::endl;
    print_out_combinations(pTempRange, iN, 0);
    return 0;
}

其他提示

你的解决方案将永远只能工作n=2。考虑使用一系列(梳)与n整数,再循环将会勾起来的最后一项数。当,项目达到最大的更新,然后梳[n-2]项和设定的最后一个项目前的价值+1.

基本上工作就像一个时钟,但你需要逻辑找到什么要提升和什么未来的最低值。

看起来像一个很好的问题递归。

定义功能 f(prefix, iMin, iMax, n), 那打印的所有组合 n 数字的范围[iMin, iMax]和返回总数的组合。对于 n =1,它应该打印的每一位从 iMiniMax 和返回 iMax - iMin + 1.

你的 iRange = 5n = 3 种情况下,你的呼叫 f("", 1, 5, 3).输出应 123 - 124 - 125 - 134 - 135 - 145 - 234 - 235 - 245 - 345.

注意到第一组产出的简单 1 作为前缀到的产出 f("", 2, 5, 2), 即 f("1", 2, 5, 2), ,随后通过 f("2", 3, 5, 2)f("3", 4, 5, 2).看看你会怎么做,用一个循环。此之间,情况 n =1所述,和陷阱不良的投入(最好的,如果他们打印什么和返回0,它应该简化循环)中,应该能够写 f().

我停止短,因为这看起来像一个家庭作业。这足以让你开始的?

编辑:只是为了笑声,我写了一蟒蛇的版本。蟒蛇有一个容易的时候周围投掷集和列表的事情,并保持清晰可见。

#!/usr/bin/env python

def Combos(items, n):
    if n <= 0 or len(items) == 0:
        return []
    if n == 1:
        return [[x] for x in items]
    result = []
    for k in range(len(items) - n + 1):
        for s in Combos(items[k+1:], n - 1):
            result.append([items[k]] + s)
    return result

comb = Combos([str(x) for x in range(1, 6)], 3)
print len(comb), " - ".join(["".join(c) for c in comb])

注意, Combos() 不关心这种类型的项目 items 名单。

这里有一个例子的一个普通的递归的解决方案。我相信存在一个更多的最佳方式实现的,如果你替换用递归的循环。这可能是你的家庭作业)

#include <stdio.h>

const int iRange = 9;
const int n = 4;


// A more efficient way to calculate binomial coefficient, in my opinion
int Cnm(int n, int m)
{
    int i;
    int result = 1;

    for (i = m + 1; i <= n; ++i)
        result *= i;

    for (i = n - m; i > 1; --i)
        result /= i;

    return result;
}


print_digits(int *digits)
{
    int i;
    for (i = 0; i < n; ++i) {
        printf("%d", digits[i]);
    }
    printf("\n");
}

void plus_one(int *digits, int index)
{
    int i;

    // Increment current digit
    ++digits[index];

    // If it is the leftmost digit, run to the right, setup all the others
    if (index == 0) {
        for (i = 1; i < n; ++i)
            digits[i] = digits[i-1] + 1;
    }
    // step back by one digit recursively
    else if (digits[index] > iRange) {
        plus_one(digits, index - 1);
    }
    // otherwise run to the right, setting up other digits, and break the recursion once a digit exceeds iRange
    else {
        for (i = index + 1; i < n; ++i) {
            digits[i] = digits[i-1] + 1;

            if (digits[i] > iRange) {
                plus_one(digits, i - 1);
                break;
            }
        }
    }
}

int main()
{
    int i;
    int digits[n];

    for (i = 0; i < n; ++i) {
        digits[i] = i + 1;
    }

    printf("%d\n\n", Cnm(iRange, n));

    // *** This loop has been updated ***
    while (digits[0] <= iRange - n + 1) {
        print_digits(digits);
        plus_one(digits, n - 1);
    }

    return 0;
}

这是我的C++的功能,与不同的接口(根据sts::set),但执行同一任务:

typedef std::set<int> NumbersSet;
typedef std::set<NumbersSet> CombinationsSet;

CombinationsSet MakeCombinations(const NumbersSet& numbers, int count)
{
  CombinationsSet result;

  if (!count) throw std::exception();

  if (count == numbers.size())
  {
    result.insert(NumbersSet(numbers.begin(), numbers.end()));
    return result;
  }

  // combinations with 1 element
  if (!(count - 1) || (numbers.size() <= 1))
  {
    for (auto number = numbers.begin(); number != numbers.end(); ++number)
    {
      NumbersSet single_combination;
      single_combination.insert(*number);
      result.insert(single_combination);
    }
    return result;
  }

  // Combinations with (count - 1) without current number
  int first_num = *numbers.begin();
  NumbersSet truncated_numbers = numbers;
  truncated_numbers.erase(first_num);
  CombinationsSet subcombinations = MakeCombinations(truncated_numbers, count - 1);

  for (auto subcombination = subcombinations.begin(); subcombination != subcombinations.end(); ++subcombination)
  {
    NumbersSet cmb = *subcombination;
    // Add current number
    cmb.insert(first_num);
    result.insert(cmb);
  }

  // Combinations with (count) without current number
  subcombinations = MakeCombinations(truncated_numbers, count);
  result.insert(subcombinations.begin(), subcombinations.end());

  return result;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top