C/C++ | 全排列 | next_permutation | prev_permutation | 常规全排列

全排列

next_permutation

这里一般先用快排sort对原有数组进行排序

// next_permutation example
#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort, std::reverse
using namespace std;
int main () {
  int myints[] = {1,2,3};

  sort (myints,myints+3);

  cout << "The 3! possible permutations with 3 elements:\n";
  do {
    cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( next_permutation(myints,myints+3) );

  cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}

输出

The 3! possible permutations with 3 elements:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
After loop: 1 2 3

prev_permutation

sort排序后用reverse进行翻转

// next_permutation example
#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort, std::reverse
using namespace std;
int main () {
  int myints[] = {1,2,3};

  sort (myints,myints+3);
  reverse (myints,myints+3);

  cout << "The 3! possible permutations with 3 elements:\n";
  do {
    cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( prev_permutation(myints,myints+3) );

  cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}

输出

3 2 1
3 1 2
2 3 1
2 1 3
1 3 2
1 2 3
After loop: 3 2 1

递归全排列

void perm(int arr[], int begin,int end){
    {
    //这里进行赋值或者输出操作
    }
    for(int j=begin;j<=end;j++){    
        swap(begin,j);        //for循环将begin~end中的每个数放到begin位置中去
        perm(arr,begin+1,end);    //假设begin位置确定,那么对begin+1~end中的数继续递归
        swap(begin,j);        //换过去后再还原
    }
}

 

例子

class Solution1 {
public:
    vector<string> permutation(string S) {
         vector<string> ret;
         dfs(ret, 0, S);
         return ret;
    }

    void dfs(vector<string>& ret, int index, string s) {
        if (index >= s.size()) {
            ret.push_back(s);
            return;
        }
        for (int i = index; i < s.size(); ++i) {
            swap(s[i], s[index]);
            dfs(ret, index + 1, s);
            swap(s[i], s[index]);
        }
    }
};
class Solution2 {
public:
    vector<string> ans;
    vector<string> permutation(string S) {
        dfs(S, 0);
        return ans;
    }

    void dfs(string S, int idx) {
        int n = S.size();
        if (idx == n) ans.emplace_back(S);
        for (int i = idx; i != n; ++i) {
            string tmp = S;
            swap(tmp[idx], tmp[i]);
            dfs(tmp, idx + 1);
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值