现在的位置: 首页 > 综合 > 正文

Permutations — leetcode

2018年10月18日 ⁄ 综合 ⁄ 共 601字 ⁄ 字号 评论关闭

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> > ans;
        helper(ans, 0, num);
        return ans;
    }

    void helper(vector<vector<int> > &ans, size_t start, vector<int> &num) {
        if (start+1 >= num.size())
                return ans.push_back(num);

        for (size_t i=start; i<num.size(); i++) {
                swap(num[start], num[i]);
                helper(ans, start+1, num);
                swap(num[start], num[i]);
        }
    }
};

抱歉!评论已关闭.