数字选择问题
有一組數(shù)字,如 “1888”,“245”,“666”,“555”,“444” , 每個(gè)數(shù)中選取一個(gè)數(shù)(或跳過(guò)),構(gòu)成一個(gè)新數(shù)字:其中的每個(gè)數(shù)都是遞增的。
"1888" ---》 1"245" ---》 2"666" ---》 6"555" ---》 跳過(guò)"444" ---》 跳過(guò)則形成為新數(shù)為126, 這也是能形成的數(shù)字個(gè)數(shù)最多的數(shù)。
要求當(dāng)這組數(shù)有N個(gè)數(shù)據(jù)時(shí)(上例中有5個(gè)數(shù)據(jù)),每個(gè)數(shù)據(jù)的長(zhǎng)度不定(上例中第1個(gè)數(shù)為4位,其它均為3位),選擇規(guī)則不變,實(shí)現(xiàn)形成的新數(shù)字個(gè)數(shù)最多。
分析
-
1、此問(wèn)題是求最優(yōu)解,因此需要全部遍歷可能成的數(shù)據(jù),然后找到最長(zhǎng)的數(shù)。
-
2、采用回溯算法,類(lèi)似八皇后問(wèn)題,可以很直觀的解決這個(gè)問(wèn)題。
假設(shè)有n個(gè)數(shù),平均長(zhǎng)度為m,則空間為O(n*m),時(shí)間為(m^n),由于數(shù)字僅有0~9,因此在時(shí)間上是存在上限的(如果采用遞歸就是展開(kāi)的次數(shù))。 -
3、一些優(yōu)化點(diǎn),如數(shù)據(jù)中去重,或當(dāng)遇到9后,停止遍歷等,可以在實(shí)現(xiàn)后在加入。
-
4、存在更優(yōu)的算法,通過(guò)空間來(lái)?yè)Q取時(shí)間。
以下為實(shí)現(xiàn)參考
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/time.h>char *num_arry[] = /* Input Data, Maybe Read from file. */ {"1888","245","666","555","444" };int result = 0; /* Final max Length of NEW Number. */ int column = 0; /* Data Grops : sizeof(num_arry)/sizeof(char *) */ int solution_num = 0; /* all solution numbers */#define DEBUG 1#ifdef DEBUG #define MAX_NUMBER_GROUP (100) #define MAX_CORE_TIMES (10*10*10*10*10*10*10)int call_core_time = 0; char result_buf_tmp[MAX_NUMBER_GROUP] = {0}; /* Temp buffer to Record process. */ char result_buf_max[MAX_NUMBER_GROUP] = {0}; /* Final Result. */#endifint get_path(char chr, int depth, int hop) {int i = 0;#ifdef DEBUGif(call_core_time++ > MAX_CORE_TIMES){printf("[%s][%d]error happen.\n", __FUNCTION__, __LINE__);exit(-1);} #endifif(depth >= column){ #ifdef DEBUGresult_buf_tmp[depth] = '\0';printf("Get Hop = %d, path:%s\n", hop, result_buf_tmp);fflush(stdout); #endifsolution_num++;if(result < hop){#ifdef DEBUGstrcpy(result_buf_max, result_buf_tmp); #endifresult = hop;}return;}for(i = 0; i < strlen(num_arry[depth]); i++){if(num_arry[depth][i] > chr){ #ifdef DEBUGresult_buf_tmp[depth] = num_arry[depth][i]; #endifget_path(num_arry[depth][i], depth + 1, hop + 1);}}/* the last is '\0', just skip it. */ #ifdef DEBUGresult_buf_tmp[depth] = '*'; #endifget_path(chr, depth + 1, hop); }int main(void) {int i = 0;struct timeval t1;struct timeval t2;column = sizeof(num_arry) / sizeof(char *);for(i = 0; i < column; i++){printf("[Input %d] %s:%d\n", i , num_arry[i], strlen(num_arry[i]));}printf("[%s][%d] Start...\n", __FUNCTION__, __LINE__);gettimeofday(&t1, NULL);/* Real work Start... */get_path(0, 0, 0);gettimeofday(&t2, NULL);printf("[%s][%d] End. Result : %d\n", __FUNCTION__, __LINE__, result);printf("Use time : %d ms\n", (t2.tv_sec - t1.tv_sec) * 1000 * 1000 + t2.tv_usec - t1.tv_usec);#ifdef DEBUGprintf("Result call_core_time: %d, all call_core_time:%d\n", solution_num, call_core_time);printf("result number is : %s\n", result_buf_max); #endifreturn 0; }總結(jié)
- 上一篇: 嵌入式新人发展的总体方向
- 下一篇: 板子上wget移植