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], and [3,2,1].

class Solution {
public:
    void _swap (int &a, int &b) {
        int tmp = a;
        a = b;
        b = tmp;
    }
    bool exist(vector<int>& nums, int num, int start, int end) {
        int i = 0;
        for (i=start; i<end; i++) {
            if (nums[i] == num) {
                return true;
            }
        }
        return false;
    }
    void _permute(vector<vector<int>> &res, vector<int>& nums, int start, int end) {

        if (start >= end) {
            res.push_back(nums);
            return;
        }
        int i;
        for (i=start; i<=end; i++) {
            /*
            if (exist(nums, nums[i], start, i)) {
                continue;
            }
            */
            _swap(nums[start], nums[i]);
            _permute(res, nums, start+1, end);
            _swap(nums[start], nums[i]);
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> res;
        int start = 0;
        int end = nums.size() - 1;
        _permute(res, nums, start ,end);
        return res;
    }
};
原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5184767.html