从1到N这N个数中取M个数,将这M个数从大到小输出,将所有的组合顺序输出

题目:从1到N这N个数中取M个数,将这M个数从大到小输出,将所有的组合顺序输出。例如N=5,M=3,输出如下:

4 3

5 4 2

5 4 1

5 3 2

5 3 1

5 2 1

4 3 2

4 3 1

4 2 1

3 2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一个经典的组合问题,可以使用递归来解决。我们可以定义一个递归函数来生成这个组合列表。函数接受四个参数:当前正在处理的数字、需要选择的数字个数、当前已经选择的数字和生成的组合列表。 下面是一个示例代码: ``` void generate_combinations(int current, int count, string current_combination, vector<string>& combinations) { // 基本情况:已经选择了需要的数字个数 if (count == 0) { combinations.push_back(current_combination); return; } // 递归情况:选择当前数字或者不选择当前数字 if (current <= 9) { generate_combinations(current + 1, count - 1, current_combination + to_string(current), combinations); generate_combinations(current + 1, count, current_combination, combinations); } } ``` 这个函数首先检查是否已经选择了需要的数字个数。如果是,则将当前组合添加到列表中并返回。否则,它将递归地调用自身两次:一次选择当前数字,一次不选择当前数字。 我们可以在主函数中调用这个函数来生成组合列表: ``` int main() { int n = 3, m = 2; vector<string> combinations; generate_combinations(1, m, "", combinations); sort(combinations.begin(), combinations.end()); for (string combination : combinations) { cout << combination << " "; } return 0; } ``` 在这个例子中,我们将n设置为3,将m设置为2,然后调用generate_combinations函数来生成组合列表。最后,我们将列表排序并输出输出结果为:12 13 23

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值