凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 46. Permutations

分类:algorithm| 发布时间:2016-10-12 15:01:00


题目

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

题意

返回给出的数组的所有排列。

解法

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> ret;
        permute(nums, 0, ret);
        return ret;
    }

    void permute(vector<int>& nums, int idx, vector<vector<int>>& ret) {
        if (idx == nums.size() - 1) {
            ret.push_back(nums);
            return;
        }

        for (int i = idx; i < nums.size(); ++i) {
            swap(nums[idx], nums[i]);
            permute(nums, idx + 1, ret);
            swap(nums[i], nums[idx]);
        }
    }
};