全排列的递归和非递归实现(permutation)(C++)

全排列问题

具体问题描述和思路请参考这篇文章:
http://blog.csdn.net/morewindows/article/details/7370155/

以下是C++代码实现:

//Permutation1 和 permutation2 分别是基于递归和非递归的实现,都可以实现去除重复的排列
//读者也可以自己提交之后到leetcode47 题提交以下,看自己写的对不对

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

bool isswap(vector<int> &arr, int begin, int end){
    for(int i = begin;i < end;i++){
        if(arr[i] == arr[end])
            return false;
    }
    return true;
}

void permutation1(vector<int> &arr, int start, int len, vector<vector<int>> &res){
    if(start == len){
        res.push_back(arr);
        return ;
    }
    for(int i = start; i <= len;i++){
        if(isswap(arr, start, i) == true){
            swap(arr[start], arr[i]);
            permutation1(arr, start+1, len, res);
            swap(arr[start], arr[i]);
        }
    }
}


void permutation2(vector<int> &arr, int start, int len, vector<vector<int>> &res){
    sort(arr.begin(), arr.end());
    res.push_back(arr);
    bool flag = false;
    int i, j, k;
    while(true){
        for(i = len;i > start;i--){
            if(arr[i-1] < arr[i])
                break;
        }
        if(i == start)
            break;
        j = i - 1;
        for(k = len;k > j;k--){
            if(arr[k] > arr[j])
                break;
        }
        swap(arr[k], arr[j]);
        res.push_back(arr);
        sort(arr.begin()+j+1, arr.end());
    }
}



int main(){
    int arr1[4] = {1, 2, 3, 4};
    vector<int> arr(arr1, arr1+4);
    vector<vector<int>> res;
    int start = 0;
    int len = 3;

    //permutation1(arr, start, len, res);

    permutation2(arr, start, len, res);

    for(unsigned int i = 0;i < res.size();i++){
        for(unsigned int j = 0;j < res[i].size();j++){
            cout<<res[i][j]<<" ";
        }
        cout<<endl;
    }
    getchar();
    return 0;
}
点赞