leetcode 46. Permutations 搜索

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

DFS

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> res;
        dfs(nums, 0, res);
        return res;
    }
    void dfs(vector<int> &num, int begin, vector<vector<int>>& res){
        if(begin>=num.size()){
            res.push_back(num);
            return ;
        }
        for(int i=begin;i<num.size();i++){
            swap(num[begin], num[i]);
            dfs(num, begin+1, res);
            swap(num[begin], num[i]);
        }
    }
};
posted @ 2020-07-26 10:05  winechord  阅读(50)  评论(0编辑  收藏  举报