Leetcode:permutation Sequence

Source: Internet
Author: User

permutation Sequence
The set [,..., 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):
"123"
"132"
"213"
"231"
"312"
"321"
Given N and K, return the kth permutation sequence.

Note:given n would be between 1 and 9 inclusive.

classSolution { Public:stringGetpermutation (intNintK) {intptable[Ten] = {1}; for(inti =1; I <=9; i++) {Ptable[i] = i * ptable[i-1]; }stringResult vector<char>numset{' 1 ',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ',' 8 ',' 9 '}; while(N >0){inttemp = (K-1)/Ptable[n-1];            Result + = Numset[temp];            Numset.erase (Numset.begin () + temp); K = k-temp * Ptable[n-1];        n--; }returnResult }};/*in This program, ptable refers to permutation table and Numset refers to a set of numbers from 1 to 9. Before while loop, we need to initialize ptable and Numset, which is trivial. In and loop, we do these following things.1 calculate which number we'll use.2 remove that number from Numset.3 Recalc Ulate k.4 N--. Finally, we return result.*/

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode:permutation Sequence

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.