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

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

void nextPermutation(vector<int>& nums) {
    int n = nums.size(), i, j;
    for(i = n-2; i >= 0; i--)
    {
        if(nums[i+1] > nums[i])
        {
            reverse(nums.begin()+i+1, nums.end()); //或sort
            for(j = i+1; j < n; j++)
            {
                if(nums[j] > nums[i])
                {
                    nums[i] = nums[i] ^ nums[j];
                    nums[j] = nums[i] ^ nums[j];
                    nums[i] = nums[i] ^ nums[j];
                    break;
                }
            }
            return;
        }
    }
    if(i < 0)
        reverse(nums.begin(), nums.end()); //或sort
}

 

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