非遞迴的輸出1-N的全排列執行個體(推薦),遞迴1-n

來源:互聯網
上載者:User

非遞迴的輸出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的全排列執行個體(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.