LeetCode_Permutations

Given a collection of numbers, return all possible permutations.



For example,

[1,2,3] have the following permutations:

[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]

  找全排列,DFS的一般应用

class Solution {

public:

   void DFS(vector<int> &num, int size,vector<int> temp)

    {

        if(size == n){

            result.push_back(temp);

            return ;

        }

        for(int i = 0; i< n; i++)

        {

           if(flag[i] == false)

           {

                temp[size] = num[i];

                flag[i] = true;

                DFS(num, size+1, temp);

                flag[i] = false;

           }

        }

    }

    vector<vector<int> > permute(vector<int> &num) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        n = num.size();

        result.clear();

        flag.resize(n,false);

        

        if(n == 0) return result;

        vector<int> temp(n,0) ;         

        DFS(num,0,temp);   

        

        return result ;

    }

private :

   int  n;

   vector<bool> flag;

   vector<vector<int>> result;   

};

 

你可能感兴趣的:(LeetCode)