leetcode排列,求第k個排列

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   

stl 中的下一個排列在寫一遍忘了

寫個1個多小時,使用遞迴寫的,錯誤就在我使用一個list儲存當前剩下的數,然後利用k/(n-1)!的階乘就是刪除的數字,但進過觀察,

比如 list={1,2,3}

分成3組:

1  {2,3}

2 {1,3}

3 {1,2}

確定位於哪個組,然後確定位於哪個組的第幾個nyoj 511。

求第3個排列   ,3%2=1,刪除 list就是第3個數3,其實呢是第2個樹2 ,所以   計算方法為 (k-1)/(n-1)!

另外一個對於下一組,k%(n-1)!也不行啊,   第4個, 4%2!=0,其實應該為第二2.

這個思路和nyoj的小球下落很像(nyoj 511)

 1 public class Solution { 2      3     private String ans=""; 4     public int calu(int n) 5     { 6         if(n==0) return 1; 7         int sum=1; 8         for(int i=2;i<=n;i++) 9         {10             sum*=i;11         }12         return sum;13     }14     15     public String getPermutation(int n, int k) {16         ArrayList<Integer> arry=new ArrayList<Integer>();17         for(int i=1;i<=n;i++)18         {19             arry.add(i);20         }21         22         get(k,calu(n-1),arry);23         return ans;24         25     }26     public void get(int k,int n1,ArrayList<Integer> list)27     {28         if(list.size()==1)29         {30             ans+=list.remove(0);31             return;32         }33            int a=list.remove((k-1)/n1);34            ans+=a;35            int te=k%n1;36            if(te==0) te=n1;37         get(te,n1/list.size(),list);38         39         40     }41 }
View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.