數組的全排列算法


原文

求給定數組的全排列。

如:

輸入:

3,4,5

輸出:

3 4 5 
3 5 4 
4 3 5 
4 5 3 
5 4 3 
5 3 4

思路:

1. 首先看最后兩個數4, 5。 它們的全排列為4 5和5 4, 即以4開頭的5的全排列和以5開頭的4的全排列。
由於一個數的全排列就是其本身,從而得到以上結果。

2. 再看后三個數3, 4, 5。它們的全排列為3 4 5、3 5 4、 4 3 5、 4 5 3、 5 3 4、 5 4 3 六組數。
即以3開頭的和4,5的全排列的組合、以4開頭的和3,5的全排列的組合和以5開頭的和3,4的全排列的組合.
從而可以推斷,設一組數p = {r1, r2, r3, ... ,rn}, 全排列為perm(p),pn = p - {rn}。
因此perm(p) = r1perm(p1), r2perm(p2), r3perm(p3), ... , rnperm(pn)。當n = 1時perm(p} = r1。

3. 為了更容易理解,將整組數中的所有的數分別與第一個數交換,這樣就總是在處理后n-1個數的全排列。

代碼:

#include <iostream>  
#include <vector>  
using namespace std;  
  
void permutation(vector<vector<int>>& res, vector<int>& num, int index){  
    if(index >= num.size()){  
        res.push_back(num);  
        return;  
    }  
    for(int i = index; i < num.size(); i++){  
        swap(num[i], num[index]);  
        permutation(res, num, index+1);  
        swap(num[index], num[i]);  
    }  
}  
  
int main(int argc, const char * argv[]) {  
    vector<vector<int>>res;  
    vector<int> vec={3,4,5};  
    permutation(res, vec, 0);  
    for(int i = 0; i < res.size(); i++){  
        for(int j = 0; j < res[0].size(); j++)  
            cout<<res[i][j]<<" ";  
        cout<<endl;  
    }  
    return 0;  
}  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM