zoukankan      html  css  js  c++  java
  • #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$  的格式了!! 恰饭恰饭去了

  • 相关阅读:
    Kotlin 数据类与密封类
    Kotlin 扩展
    Kotlin 接口
    Kotlin 继承
    Kotlin 类和对象
    Kotlin 循环控制
    Kotlin 条件控制
    Kotlin 基础语法
    freemarker的简单入门程序
    json数据格式的简单案例
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10008212.html
Copyright © 2011-2022 走看看