有的时候需要遍历所有的可能性,但是如果通过一般方法,由于这种可能性会有很多,循环有很多重,怎么办呢?用递归可以的。
这里面有一个前提就是,所有备选集合都是相同的,请思考如果是不同的呢?
#include <iostream>
#include <vector>
#include <stack>
/************************************************************************/
/*
题目来源: 从1-9中任选四个数字(数字可以有重复),使四个数字的和刚好是24。
简单解释: 数字都是个位数,可以重复且之用加法,循环算法的核心就是使用四重循环穷举所有的数字组合,对每一个数字组合进行求和,判断是否是24
扩展思考: N个数字的组合,可以重复,遍历所有组合
*/
/************************************************************************/
using namespace std;
const unsigned int NUMBER_COUNT = 4; // N
const int NUM_MIN_VALUE = 1; // the boundary of available number range
const int NUM_MAX_VALUE = 6; // the boundary of available number range
const unsigned int FULL_NUMBER_VALUE = 24; // summation is 24, this is one condition
int counter = 0;
void PrintNumbers(int *numbers, int NUMBER_COUNT)
{
cout << counter++ << ": ";
for (int i = 0; i < NUMBER_COUNT; i++)
{
cout << numbers[i] << " ";
}
cout << endl;
}
void EnumNumbers(int *numbers, int level, int total) // level is the index of numbers
{
int i;
for(i = NUM_MIN_VALUE; i <= NUM_MAX_VALUE; i++) // the boundary of available number range, this could be different as candidate sets may differ
{
numbers[level] = i; // this means all positions have the same candidates from MIN to MAX
if(level == (NUMBER_COUNT - 1)) // if all the number is filled, print them
{
// if(i == total) // this could be the condition, e.g. the summation is 24
{
PrintNumbers(numbers, NUMBER_COUNT);
}
}
else // if not full, put values into another layers
{
EnumNumbers(numbers, level + 1, total - i);
}
}
}
void PrintAllSResult(void)
{
int numbers[NUMBER_COUNT] = { 0 }; // the depth of the stack or number of tree layers
EnumNumbers(numbers, 0, FULL_NUMBER_VALUE); // number and 0 is the input, FULL_NUMBER_VALUE is the condition
}
int main()
{
//cout << "Hello World"<< endl;
PrintAllSResult();
cout << pow(NUM_MAX_VALUE - NUM_MIN_VALUE + 1, (double)NUMBER_COUNT) << " combinations"<< endl;
}
counter = 1;
def combinations(line,n,SETS_LEN):
global counter
for i in range(0,SETS_LEN[n]):
line[n] = SETS[n][i]
if n == NUM_of_LOOPS-1:
print counter, line
counter = counter + 1
else:
combinations(line,n+1,SETS_LEN)
a = ['1','2','3']
b = ['a','c']
c = ['A','K']
NUM_of_LOOPS = 3
SETS_LEN = [3,2,2]
SETS = [a,b,c]
line = [-1,-1,-1]
if __name__ == '__main__':
combinations(line,0,SETS_LEN)