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);
        }
    }
   
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值