`
SunnyYoona
  • 浏览: 367199 次
社区版块
存档分类
最新评论

[LeetCode]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,31,3,2
3,2,11,2,3
1,1,51,5,1

【分析】

(1)From right to left,find first digit which violate the increase call it partitionNumber

(2)partitionNumber = -1 indicate largest ,should (3),if notFrom right to left,find first digit which large than partitionNumbercall it changeNumber

swap the partition index and changeNumber

(3)reverse all the digit on the right of partition index

【代码】

/*********************************
*   日期:2015-01-16
*   作者:SJF0115
*   题目: 31.Next Permutation
*   网址:https://oj.leetcode.com/problems/next-permutation/
*   结果:AC
*   来源:LeetCode
*   博客:
**********************************/
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        int count = num.size();
        if(count == 0 || count == 1){
            return;
        }//if
        // From right to left,find first digit which violate the increase
        // call it partitionNumber
        int index;
        for(index = count-2;index >= 0;index--){
            if(num[index+1] > num[index]){
                break;
            }//if
        }//for
        int tmp;
        // -1 indicate largest
        if(index != -1){
            // From right to left,find first digit which large than partitionNumber
            // call it changeNumber
            for(int i = count-1;i > index;i--){
                if(num[index] < num[i]){
                    // swap the partition index and changeNumber
                    tmp = num[index];
                    num[index] = num[i];
                    num[i] = tmp;
                    break;
                }//if
            }//for
        }//if
        // reverse all the digit on the right of partition index
        for(int i = index+1,j = count - 1;i < j;i++,j--){
            tmp = num[i];
            num[i] = num[j];
            num[j] = tmp;
        }//for
    }
};

int main(){
    Solution solution;
    vector<int> num;
    num.push_back(1);
    num.push_back(1);
    num.push_back(5);
    // 重新排列
    solution.nextPermutation(num);
    // 输出
    for(int i = 0;i < num.size();i++){
        cout<<num[i];
    }
    cout<<endl;
    return 0;
}


分享到:
评论

相关推荐

    31.Next Permutation 下一个排列【LeetCode单题讲解系列】

    31.Next_Permutation_下一个排列【LeetCode单题讲解系列】

    leetcode答案-exercise-book:算法练习记录

    Permutation 解决方法:掌握排列组合的字典序规律,即可。这个规律找不到,我最后还是直接看答案的。 LeetCode: 581. Shortest Unsorted Continuous Subarray 解决方法:无序列中最大最小值 2018-08-17 19:47 ...

    LeetCode最全代码

    # [LeetCode](https://leetcode.com/problemset/algorithms/) !... Up to date (2016-12-18), there are `447` Algorithms / `13` ...31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| ...

    leetcode装最多水-Leetcode:解决了leetcode问题

    Permutation 算法也可用于迭代地查找数组的排列。 也可用于迭代查找数组的排列。 13 . 14 . 15 . 16 . 17 . Algorithm to find kth largest element from an unsorted array in linear time. (1) If the number of ...

    leetcode1004-leetcode:leetcode

    Permutation (M) * -&gt; index 주의, 부등호 하나 틀림 33. Search in Rotated Sorted Array (M) * -&gt; 부등호 주의, 부등호 하나 틀림 34. Find First and Last Position of Element in Sorted Array (M) 35. Search ...

    leetcode最大连通域-leetcode:leetcode

    next_permutation.py - 将数字重新排列为按字典顺序排列的下一个更大的数字排列 permutations2.py - 返回所有可能的唯一排列 3sum_2.py - 查找数组中所有唯一的三元组,其总和为零。 3sum.py - 查找数组中所有唯一的...

    lrucacheleetcode-leetcode-journal:记录所有LeetCode挑战的存储库

    lru缓存leetcode 力扣日记 欢迎来到我的 LeetCode 期刊库。 我的每个问题都将包括一个初始计划阶段,在这个阶段我将用我自己的话来...Permutation (Medium) 34. Find First and Last Position of Element in Sorted Arr

    leetcode2sumc-Leetcode_imp_C:Leetcode在C上的实现

    leetcode_0031_next_permutation.c leetcode_0033_search_rotate.c : binary search, offer11 81 leetcode_0034_first_last_pos.c : binary search leetcode_0035_search_inseart.c : binary search leetcode...

    戳气球leetcode-leetcode:leetcode

    leetcode category other hot keywords:Palindrome(mic), Subsequence Array 螺旋矩阵Spiral Matrix 顺时针打印矩阵 Next Permutation Product of Array Except Self 189.rotate-array 283.move-zero Range Sum ...

    leetcode分类-contest.js:准备比赛使用!纯JavaScript中的数据结构和算法,零依赖

    nextPermutation 等。 : KMP, RabinKarp : 路径压缩、按秩合并。 : 质数测试、筛选等。 : 阶乘、模阶乘、二项式系数、帕斯卡三角。 : 欧几里得公约数,扩展欧几里得,模拟元。 : create2DArray, create3DArray, ...

    最低加油次数leetcode-Leetcode:力码

    最低加油次数 ...Next_permutation Stack, trick trick TOP 类似斐波拉契,一层层处理 字符串处理 TOP 完全背包 dfs Trick TOP next_permutation dfs or stl next_permutation dfs or stl TOP 排序后的字符串作

    LeetCode:LeetCode练习

    STL算法常用函数:分隔组合:next_permutation()是检索当前范围内的划分,并重新排序为下一个替换,leetcode 556下一个元素元素III prev_permutation()是替换指定范围内的序列重新排列它重新排序为上一个序列。...

    lrucacheleetcode-LeetCode:这个库用于总结leetcode中遇到的习题,期望按照数据结构和常用方法分成2类,进行总结,

    lru cache leetcode LeetCode 这个库用于总结leetcode中遇到的习题 常用数据结构习题总结 1.线性表 解决进度 ...Next Permutation 公式 13 Permutation Sequence 公式 14 Valid Sudoku 15 Trapping Rain W

    leetcode最大蓄水量-leetcode_note_book:leetcode题目分类及刷题总结

    NextPermutation 下一排序 完成 DFS 题目 说明 状态 NumIslands 岛屿数量 完成 DivideAndConquer 题目 说明 状态 MaxSubArray 最大子序和 完成 Back Tracing 题目 说明 状态 GenerateParenthesis 括号生成 完成 ...

    leetcode:leetcode回购

    密码 leetcode回购 树 - - - - 杂凑 - - 二元搜寻 0004_findMedianSortedArrays - SLN 0033_search - SLN 0034_searchRange - SLN 0035_searchInsert - SLN ...0031_nextPermutation - SLN

    leetcode中国-leetcode:力码

    leetcode中国 LeetCode | LuoGu 题型记录 P1980 计数问题 (数位dp, 朴素算法) P1047 校门外的树 (线段树, ...全排列问题(next_permutation, dfs(最主要需要记住,置位后需要清0(f[i]=0))) P3392 涂国旗(组合) P23

    leetcode演示

    NextPermutation SearchInRotatedSortedArray SearchInRotatedSortedArrayII FindMinimumInRotatedSortedArray FindMinimumInRotatedSortedArrayII FindPeakElement SearchRangeInSortedArray Search...

    javalruleetcode-SDE-Problems:标准SDE问题列表

    leetcode SDE-问题 标准 SDE 问题列表 第一天:(数组) 日 问题陈述 解决方案 困难 使用的数据结构 使用的算法 时间复杂度 空间复杂度 补充阅读 在 N 个整数的数组中查找重复项 中等的 大批 不适用 上) O(1) 在不...

    cpp-算法精粹

    Next Permutation Permutation Sequence Valid Sudoku Trapping Rain Water Rotate Image Plus One Climbing Stairs Set Matrix Zeroes Gas Station Candy Majority Element Rotate Array Contains Duplicate ...

Global site tag (gtag.js) - Google Analytics