LeetCode 46. Permutations

Given a collection of distinct 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],
  [3,2,1]
]

明显的全排列,直接用C++里面全排列函数写一遍,最后发现数组存在负数情况时,会莫名少了好多情况, 于是直接DFS手写一个全排列。

class Solution
{
    void dfs(int b, int e, vector<int>& nums, vector<vector<int>> &ans)
    {
        if(b == e)
        {
            ans.push_back(nums);
            return;
        }
        for(int i=b; i <= e; ++ i)
        {
            swap(nums[i], nums[b]);
            dfs(b+1, e, nums, ans);
            swap(nums[i], nums[b]);
        }
    }

    public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> ans;
        dfs(0, nums.size() - 1, nums, ans);
        return ans;
    }
};

posted @ 2017-03-31 18:26  aiterator  阅读(99)  评论(0编辑  收藏  举报