閱讀469 返回首頁    go 阿裏雲 go 技術社區[雲棲]


全排列程序

算法:遞歸出口:集合中隻有一個元素時,即exPos == setNum時,打印一個排列。
           繼續遞歸條件:當exPos<setNum時,遞歸地產生前綴set[0:setNum-2],最後回到出口,結束遞歸。
過程中需要交換元素,把後麵的元素依次與第一個元素交換,這樣就可以第次隻處理後setNum-1個元素,而
依次遞歸,就可以最終到達exPos==setNum的出口條件。

#include <iostream>


using namespace std;

//list is the whole set.
//exPos is the position to exchange with the first element.
//the numbers of the whole set.
void  wholeArrage(char* list, int exPos, int setNum);
inline void Swap(char& c1, char& c2);

int main()
{
    char set[] = {'a', 'b','c'};
    int setNum = 3;

    wholeArrage(set, 0, setNum);
    return 0;
}

void wholeArrage(char* list, int exPos, int setNum)
{
static int count = 0;
if (exPos == setNum-1)
{
count ++;
for (int i = 0; i < setNum; i++)
    cout << list[i];
cout << " ";
if (count % 10 == 0)
    cout << endl;
}
else
{
for (int i = exPos; i < setNum; i++)
{
Swap(list[i], list[exPos]);
wholeArrage(list, exPos+1, setNum);
            Swap(list[i], list[exPos]);
}
}

}

inline void Swap(char& c1, char& c2)
{
char tmp = c1;
c1 = c2;
c2 = tmp;
}

最後更新:2017-04-02 18:14:51

  上一篇:go Oracle操作報錯:record is locked by another user
  下一篇:go android中Intent的一些用法和總結