zoukankan      html  css  js  c++  java
  • leetcode-next permutation

    EdgeCase太容易出错。有两处都是应该为<=但写成了<。

     1 #include <iostream>
     2 #include <vector>
     3 #include <algorithm>
     4 using namespace std;
     5 
     6 class Solution2 {
     7 public:
     8     void nextPermutation(vector<int> &num) {
     9         int last = num.size() - 1;
    10     }
    11 };
    12 class Solution {
    13 public:
    14     void nextPermutation(vector<int> &num) {
    15         int last = num.size() - 1;
    16         int vioIndex = last;
    17         while (vioIndex - 1 >= 0 && num[vioIndex] <= num[vioIndex - 1])//出错点!是<=不是<![1,1]
    18         {
    19             vioIndex--;
    20         }
    21         if (vioIndex != 0)
    22         {//存在vioIndex
    23             vioIndex--;
    24             int rightIndex = last;
    25             while (num[rightIndex] <=num[vioIndex])//出错点。是<=,不是< [1,5,1]
    26                 rightIndex--;
    27             //swap vio and rightIndex
    28             int temp = num[vioIndex];
    29             num[vioIndex] = num[rightIndex];
    30             num[rightIndex] = temp;
    31             //reverse from vioIndex+1 to the end
    32             vioIndex++;
    33         }
    34 
    35         //不存在vioIndex.直接逆序就行了
    36         int beg = vioIndex;
    37         int end = last;
    38         while (beg < end)
    39         {
    40             int temp = num[end];
    41             num[end] = num[beg];
    42             num[beg] = temp;
    43             beg++; end--;
    44         }
    45 
    46         //next_permutation(num.begin(), num.end());
    47         printV(num);
    48     }
    49     void printV(vector<int> &num)
    50     {
    51         for (int i = 0; i < num.size(); i++)
    52         {
    53             //cout << (i == 0 ? num[i] : ',' << num[i]);
    54             if (i == 0)
    55                 cout << num[i];
    56             else
    57                 cout << ',' << num[i];
    58         }
    59         cout << endl;
    60     }
    61 };
    62 int main()
    63 {
    64     Solution s;
    65     int a[] = { 1,  1 };
    66     vector<int> v(a, a + 2);
    67     s.nextPermutation(v);
    68     return 0;
    69 }

    ========================================================================

    http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html

     

  • 相关阅读:
    SpringMVC 多文件上传
    get传参乱码问题
    springMVC配置
    带参sql$和#的区别(注解)
    java多线程--实现Runnable接口方式
    java复制文件夹及所有子目录和文件
    Angularjs 学习笔记
    springboot 项目 docker化部署
    docker 基础
    Java-马士兵动态代理模式
  • 原文地址:https://www.cnblogs.com/forcheryl/p/4030578.html
Copyright © 2011-2022 走看看