[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].

class Solution {
public:
    vector<vector<int> > permute(vector<int> &num) {
        vector<vector<int>> res;
        dfs(res, num, 0);
        return res;
    }
    void dfs(vector<vector<int>> &res, vector<int> &num, int cur)
    {
        if(cur == num.size())
            res.push_back(num);
        else
        {
            for(int i = cur; i < num.size(); i++)
            {
                swap(num[i], num[cur]);
                dfs(res, num, cur+1);
                swap(num[i], num[cur]);
            }
        }
    }
};

这种题目还是必须要自己动手写一遍,之前偷懒用的是STL里面的next_permutation算法,到笔试的时候不能用。还是要学会熟练的手写比较好。


你可能感兴趣的:([LeetCode] Permutations)