美文网首页
46. Permutations/全排列

46. Permutations/全排列

作者: 蜜糖_7474 | 来源:发表于2019-05-20 13:06 被阅读0次

    Given a collection of distinct integers, return all possible permutations.

    Example:

    Input: [1,2,3]
    Output:
    [
    [1,2,3],
    [1,3,2],
    [2,1,3],
    [2,3,1],
    [3,1,2],
    [3,2,1]
    ]

    AC代码

    void digui(vector<int>& nums, vector<int>& t, vector<int>& book,
               vector<vector<int>>& ans) {
        if (t.size() == nums.size()) {
            ans.push_back(t);
            return;
        }
        for (int i = 0; i < nums.size(); ++i) {
            if (book[i] == 0) {
                book[i] = 1;
                t.push_back(nums[i]);
                digui(nums, t, book, ans);
                t.pop_back();
                book[i] = 0;
            }
        }
    }
    
    class Solution {
    public:
        vector<vector<int>> permute(vector<int>& nums) {
            vector<vector<int>> ans;
            vector<int> t, book(nums.size());
            digui(nums, t, book, ans);
            return ans;
        }
    };
    

    总结

    相关文章

      网友评论

          本文标题:46. Permutations/全排列

          本文链接:https://www.haomeiwen.com/subject/czfkzqtx.html