leetcode Permutations

来源:互联网 发布:telnet端口23在哪 编辑:程序博客网 时间:2024/05/21 05:22

I'll introduce a method without using the permutation tree. 

From the right to the left, find the first num[i-1] < num [i], record ii = i-1;

Find the minimal number larger than num[ii] from ii's right. record its index jj

swap num[ii] and num[jj]

Then reverse the array from ii + 1 to end.

class Solution { public:  bool next_perm(vector<int>& num) {    int i, j, n = num.size();    for (i = n - 1; i >= 1; --i)      if (num[i - 1] < num[i])        break;    if (i > 0) {      int ii = i - 1, jj = i, min = num[jj];      for (++i; i < n; ++i) {        if (num[i] > num[ii] && num[i] < min) {          min = num[i];          jj = i;        }      }      swap(num[ii], num[jj]);      reverse(num.begin() + ii + 1, num.end());      return true;    }    return false;  }  vector<vector<int> > permute(vector<int> &num) {    // IMPORTANT: Please reset any member data you declared, as    // the same Solution instance will be reused for each test case.    vector<vector<int>> res;    sort(num.begin(),num.end());    do {      res.push_back(num);    } while (next_perm(num));    return res;  }};





原创粉丝点击