LeetCode (Permutations)

来源:互联网 发布:大芒果专用数据修改 编辑:程序博客网 时间:2024/05/20 00:16

Problem:

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]]
Solution:

class Solution {public:    vector<vector<int>> permute(vector<int>& nums) {            vector<vector<int>> ans;        if (nums.empty() || nums.size() == 1){            return {nums};        }        vector<int> num = nums;        num.erase(num.begin());        vector<vector<int>> b = permute(num);        for (int j = 0; j < b.size(); j++)            for (int l = 0; l < nums.size(); l++){                vector<int> p = b[j];                p.insert(p.begin() + l, nums[0]);                ans.push_back(p);        }        return ans;    }};


0 0