非遞迴的輸出1-N的全排列執行個體(推薦),遞迴1-n
網易遊戲筆試題演算法題之一,可以用C++,Java,Python,由於Python代碼量較小,於是我選擇Python語言。
演算法總體思路是從1,2,3……N這個排列開始,一直計算下一個排列,直到輸出N,N-1,……1為止
那麼如何計算給定排列的下一個排列?
考慮[2,3,5,4,1]這個序列,從後往前尋找第一對遞增的相鄰數字,即3,5。那麼3就是替換數,3所在的位置是替換點。
將3和替換點後面比3大的最小數交換,這裡是4,得到[2,4,5,3,1]。然後再交換替換點後面的第一個數和最後一個數,即交換5,1。就得到下一個序列[2,4,1,3,5]
代碼如下:
def arrange(pos_int): #將1-N放入列表tempList中,已方便處理 tempList = [i+1 for i in range(pos_int)] print(tempList) while tempList != [pos_int-i for i in range(pos_int)]: for i in range(pos_int-1,-1,-1): if(tempList[i]>tempList[i-1]): #考慮tempList[i-1]後面比它大的元素中最小的,交換。 minmax = min([k for k in tempList[i::] if k > tempList[i-1]]) #得到minmax在tempList中的位置 index = tempList.index(minmax) #交換 temp = tempList[i-1] tempList[i-1] = tempList[index] tempList[index] = temp #再交換tempList[i]和最後一個元素,得到tempList的下一個排列 temp = tempList[i] tempList[i] = tempList[pos_int-1] tempList[pos_int-1] = temp print(tempList) break arrange(5)
以上這篇非遞迴的輸出1-N的全排列執行個體(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。