穷举算法

有的时候需要遍历所有的可能性,但是如果通过一般方法,由于这种可能性会有很多,循环有很多重,怎么办呢?用递归可以的。
这里面有一个前提就是,所有备选集合都是相同的,请思考如果是不同的呢?

#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)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值