#Leetcode# 46. Permutations

https://leetcode.com/problems/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]
]

代码:

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        int n = nums.size();
        vector<int> vis(n, 0);
        vector<vector<int>> ans;
        vector<int> v;
        
        dfs(nums, 0, ans, v, vis);
        return ans;
        
    }
    void dfs(vector<int>& nums,int step, vector<vector<int>> &ans, vector<int> &v, vector<int> &vis) {
        if(step == nums.size()) 
            ans.push_back(v);
        else {
            for(int i = 0; i < nums.size(); i ++) {
                if(vis[i] == 0) {
                    vis[i] = 1;
                    v.push_back(nums[i]);
                    dfs(nums, step + 1, ans, v, vis);
                    v.pop_back();
                    vis[i] = 0;
                }
            }
        }   
    }
};

 

全排列 $dfs$ 写就好的啦 第一次成功自己写出来下面的函数没有之前那样看到 $vector$ 就头大了 还是有点开心的! 最开始写好运行的时候除了问题乱七八糟的输出 看了半天不知道错在哪里然后自杀式交一发 WA 掉 最后怼在屏幕上看了五分钟发现把 “=” 写成 “==”  好像每一天都有更适应 $Leetcode$  的格式了!! 恰饭恰饭去了

猜你喜欢

转载自www.cnblogs.com/zlrrrr/p/10008212.html