• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
60. 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.

string getPermutation(int n, int k) {
    int total=1, idx, i;
    vector<char> nums;
    for(i = 1; i <= n; i++)
    {
        nums.push_back(i+'0');
        total *= i;
    }
    if(k>total || k<1)
        return "";
    string s;
    s.resize(n);
    i = 0;
    while(n)
    {
        total /= n;
        idx = (k-1) / total;
        s[i++] = nums[idx];
        nums.erase(nums.begin()+idx);
        k = (k-1) % total +1; //can also be k -= group * idx
        n--;
    }
    return s;
}

// Construct the k-th permutation with a list of n numbers
// Idea: group all permutations according to their first number (so n groups, each of
// (n-1)! numbers), find the group where the k-th permutation belongs, remove the common
// first number from the list and append it to the resulting string, and iteratively
// construct the (((k-1)%(n-1)!)+1)-th permutation with the remaining n-1 numbers

posted on 2016-03-11 23:43  ArgenBarbie  阅读(126)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3