数字选择问题
有一組數字,如 “1888”,“245”,“666”,“555”,“444” , 每個數中選取一個數(或跳過),構成一個新數字:其中的每個數都是遞增的。
"1888" ---》 1"245" ---》 2"666" ---》 6"555" ---》 跳過"444" ---》 跳過則形成為新數為126, 這也是能形成的數字個數最多的數。
要求當這組數有N個數據時(上例中有5個數據),每個數據的長度不定(上例中第1個數為4位,其它均為3位),選擇規則不變,實現形成的新數字個數最多。
分析
-
1、此問題是求最優解,因此需要全部遍歷可能成的數據,然后找到最長的數。
-
2、采用回溯算法,類似八皇后問題,可以很直觀的解決這個問題。
假設有n個數,平均長度為m,則空間為O(n*m),時間為(m^n),由于數字僅有0~9,因此在時間上是存在上限的(如果采用遞歸就是展開的次數)。 -
3、一些優化點,如數據中去重,或當遇到9后,停止遍歷等,可以在實現后在加入。
-
4、存在更優的算法,通過空間來換取時間。
以下為實現參考
#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; }總結
- 上一篇: 嵌入式新人发展的总体方向
- 下一篇: 板子上wget移植