深度优先搜索求全排列

#include <iostream>
using namespace std;
void dfs(int num, int * a, bool * isVisited, string temp) {
    if (temp.size() == num) {
        cout << temp << endl;
    }
    else {
        for (int i = 1; i <= num; i++) {
            if (!isVisited[i]) {
                isVisited[i] = true;
                temp += i + '0';
                dfs(num, a, isVisited, temp);
                temp = temp.substr(0, temp.size() - 1); 
                isVisited[i] = false;
            }
        } 
    }
}

void find(int num) {
    string temp = "";
    int * a = new int[num + 1];
    bool * isVisited = new bool[num + 1];
    for (int i = 1; i <= num; i++) {
        a[i] = i;
        isVisited[i] = false;
    }
    dfs(num, a, isVisited, temp);
    delete [] a;
    delete [] isVisited;
}

 

posted @ 2017-10-16 19:14  fengzw  阅读(379)  评论(0编辑  收藏  举报