leetcode #60 in cpp

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.

solution: 

We don't want to generate the kth permutation by loops. If n is n^k then this is an algorithm with exponential complexity.

The hint is actually in the question. Suppose we have n = 2. Then each of 1,2,3 would have 2 rows. In general, each of 1,2,3,.....,n would have (n-1)! rows since there are (n-1)! permutations for n-1 numbers. 

We want to get the kth number. We know that each heading, say, 1,2,4...n, would have (n-1)! rows. We could directly know that the first digit of the number is, by calculating (k-1)/(n-1)!. The first digit must by number[(k-1)/(n-1)!], given number = "123456789".   

For example, n = 3, k = 3, numbers = "123". then (3-1)/(2)! = 1 and number[1] is 2. 

Now that we have had the first digits,we proceed to get the second digit.

 Since we know the first digit, we could narrow down the range we are to search. Say n=3, k =3, and the first digit is 2, then our search range is 13, 31. Note that now our search range involves n -1 = 2 numbers, which is 1 and 3

Originally we are to get the kth number. But now we narrow down the search range, we should also narrow down k, and set k = k %(n-1)!. 

Since we have n-1 numbers now, we would have (n-1) permutations and we want to find  (k%(n-1)!)th permutation in those permutation. Wait! isn't it the same questions are our original question but with n = n-1 and k = k%(n-1)! ? It is recurrent! 

This means we could do a recurrence call, and the ith call would figure out the ith digit. Every time we update n, and k and then we could go to the next recurrent call.

Code: 

class Solution {
public:
    string getPermutation(int n, int k) {
        string res= "";
        string num = "123456789";
        long int n_1factorial = 1;//(n-1)!
        for(int i = 1; i <= n-1; i ++){
            n_1factorial *=i;
        }
        k--;//kth number points to k-1 position
        return solve(res, n, k,n_1factorial, num);
    }
    string solve(string res, int n , int k, long int n_1factorial, string &num){
        if(n==1) return res+num[0];
        else{
            res+= num[k/(n_1factorial)];
            num.erase(num.begin() + k/n_1factorial);
            return solve(res, n-1, k%(n_1factorial), n_1factorial/(n-1), num);
        }
    }
   
};



阅读更多
文章标签: cpp leetcode
个人分类: interview
上一篇leetcode #59 in cpp
下一篇leetcode #61 in cpp
想对作者说点什么? 我来说一句

LeetCode cpp最新中文题解.pdf

2018年01月10日 866KB 下载

没有更多推荐了,返回首页

关闭
关闭