leetcode之Permutation Sequence

原題如下:

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

這道題的規律性還是很強的,那就是n個數列中第一位的數字每個重複(n-1)!次,並按照從小到大的順序出現,k/(n-1)!就是第一位要出現的數字,後邊的依次類推。編程時要注意以下幾個方面:一是原數列就是第一個數列,所以需要將k首先減1,其次是在求解過程中,需要將k落入當前位及其後所能表示的範圍(所以需要對count取模),之後將count表示成當前位後邊(不包括當前位)所能表示的範圍(所以需要除以n-i),最後再求index時就是k除以count,這裏邊的主要思路就是當前位只能處理它所能處理的範圍,超出當前範圍的由其上級處理。另外就是每用掉一位,就將改爲刪除,並將其後位的數前移(數組始終保持遞增數列)。

class Solution {
public:
    string getPermutation(int n, int k) {
        vector<int>num(n);
		int count = 1;
		string str;
		for(int i = 0; i < n; i++){
		    num[i] = i + 1;
			count *= num[i];
		}
		k--;				
		for(int i = 0; i < n; i++){			
			k = k % count;
			count /=(n - i);
		    int  index = k /count;
			char c = num[index] + '0';
			str.append(1,c);
			for(int j = index; j < n - 1; j++)
				num[j] = num[j + 1];			
		}
		return str;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章