递归实现 从n个数中选取m个数的所有组合

nn>0 个数,从中选取 mn>m>0 个数,找出所有的组合情况(不分顺序)。这样的组合共有 Cmn=n×(n1)××(nm+1)m! .

一个数组 data 有 n 个元素,从中选取 m 个数的组合 arr,使用递归算法实现是这样一个过程:
1) 选择 data的第1个元素为arr的第一个元素,即:arr[0] = data[0];
2) 在data第一个元素之后的其它元素中,选取其余的 m - 1个数,这是一个上述问题的子问题,递归即可。
3) 依次选择 data的第 2 到 n - m + 1元素作为起始点,再执行1、2步骤。
4) 递归算法过程中的 m = 0 时,输出 arr 的所有元素。

C++ 代码如下:

template <typename T>
void computeAllChoices(std::vector<T> &data, int n, int outLen, int startIndex, int m, int *arr, int arrIndex)
{
    if(m == 0)
    {   
         for (int i = 0; i < outLen; i++)   
         {
            std::cout << arr[i] << "\t";
         }
         std::cout << std::endl; 

         return;
    }

    int endIndex = n - m;
    for(int i=startIndex; i<=endIndex; i++)
    {
        arr[arrIndex] = data[i];
        computeAllChoices(data, n, outLen, i+1, m-1, arr, arrIndex+1);
    }
}

测试代码如下:

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<int> data;
    for(int i = 0; i < 6; i++)
    {
        data.push_back(i+1);
    }

    int arr[3];

    computeAllChoices(data, data.size(), 3, 0, 3, arr, 0);

    return 0;
}

输出结果:
这里写图片描述

参考:
http://blog.csdn.net/wumuzi520/article/details/8087501#comments

  • 11
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Java可以实现从n个数选取m个数的所有组合。可以使用回溯算法来解决这个问题。 回溯算法的基本思路是通过递归来生成所有可能的组合。在每一步,我们选择一个数,并在剩下的数继续选择下一个数,直到选取了m个数。 下面是一个示例的Java代码实现: ```java import java.util.ArrayList; import java.util.List; public class Combination { public static void main(String[] args) { int n = 5; // 输入的总数 int m = 3; // 需要选取的数的个数 int[] nums = {1, 2, 3, 4, 5}; // 输入的数 List<List<Integer>> combinations = new ArrayList<>(); // 保存所有组合的列表 backtrack(combinations, new ArrayList<>(), nums, 0, m); // 打印所有组合 for (List<Integer> combination : combinations) { System.out.println(combination.toString()); } } private static void backtrack(List<List<Integer>> combinations, List<Integer> currCombination, int[] nums, int start, int m) { // 判断是否已经选择了m个数 if (currCombination.size() == m) { combinations.add(new ArrayList<>(currCombination)); return; } // 从剩下的数选择下一个数 for (int i = start; i < nums.length; i++) { currCombination.add(nums[i]); // 选择当前数 backtrack(combinations, currCombination, nums, i + 1, m); // 递归调用 currCombination.remove(currCombination.size() - 1); // 撤销选择 } } } ``` 这段代码将输出所有从给定的5个数选取3个数组合。运行结果如下: [1, 2, 3] [1, 2, 4] [1, 2, 5] [1, 3, 4] [1, 3, 5] [1, 4, 5] [2, 3, 4] [2, 3, 5] [2, 4, 5] [3, 4, 5] 以上就是使用Java实现从n个数选取m个数的所有组合的方法。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值