[英]All possible combinations of a word
我在接受工作面試時,他們要求我生成給定字符串的所有可能排列的列表。 我的解決方案效率低下,面試我的那個人告訴我說我應該使用遞歸。 有人知道這個問題嗎?
這是一個經典的面試問題,解決方案是這樣的:
int permu(char* str, size_t len ,size_t index )
{
size_t i = index - 1;
if(index == len) { printf ("%s\n",str); }
while (++i < len)
{
swap (str,index,i); /* swap between index and i */
permu(str, len ,index + 1 ); /* recorsion */
swap (str,index,i); /* swap back between index and i */
}
return(0);
}
注意,在此代碼中,用戶應在索引parmether中給出0,因此最好像這樣調用此函數:
int permutations(char* str, size_t len)
{
return (permu(str, len ,0));
}
static int permu(char* str, size_t len ,size_t index )
{ //....}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.