You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include<iostream>
using namespace std;
//从后往前选取选定位置i后再在前i-1个里面选取m-1个。
//如 1 2 3 4 5 中选取 3 个
//1、选取5后再在前4个里面选取2个而前4个里面选取2个又是一个子问题递归即可。
//2、如果不包含5直接选定4那么再在前3个里面选取2个而前三个里面选取2个又是一个子问题递归即可。
//3、如果也不包含4直接选取3那么再在前2个里面选取2个刚好只有两个。
//纵向看1、2、3刚好是一个for循环初值为5终值为m
//横向看该问题为一个前i-1个中选m-1的递归。
//动态规划思想
void Combination(int arr[], int nLen, int m, int out[], int outLen) {
if(m == 0) {
for (int j = 0; j < outLen; j++) {
cout << out[j] << "\t";
}
cout << endl;
return;
}
for (int i = nLen; i >= m; --i) { //从后往前依次选定一个
out[m-1] = arr[i-1]; //选定一个后
Combination(arr,i-1,m-1,out,outLen); // 从前i-1个里面选取m-1个进行递归
}
}
void PrintCombination(int arr[], int nLen, int m) {
if(m > nLen)
return;
int* out = new int[m];
Combination(arr,nLen,m,out,m);
delete [] out;
}
int main() {
int arr[5]= {1,2,3,4,5};
int nLen=5;
int m=3;
PrintCombination(arr,nLen,m);
return 0;
}