Skip to content

Latest commit

 

History

History
52 lines (44 loc) · 941 Bytes

File metadata and controls

52 lines (44 loc) · 941 Bytes

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

解析

和 subset 差不多的解决方法,都是使用回溯法。

代码

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> path;
        dfs(nums,path,res);
        return res;
    }
    void dfs(vector<int>& nums,vector<int>& path,vector<vector<int>>& res)
    {
        if(path.size()==nums.size()){
            res.push_back(path);
            return;
        }
        for(auto i:nums){
            auto pos=find(path.begin(),path.end(),i);
            if(pos==path.end()){
                path.push_back(i);
                dfs(nums,path,res);
                path.pop_back();
            }
        }
    }
};