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

    思路一:二话不说,经典题, 回溯。

     1 class Solution {
     2 public:
     3     vector<vector<int>> permute(vector<int>& nums) {
     4         sort(nums.begin(), nums.end());
     5         int len = nums.size();
     6         vector<bool> visited(len, false);
     7         vector<vector<int> > res;
     8         vector<int> tmp;
     9         dfs(0, len, nums, tmp, res, visited);
    10         return res;
    11     }
    12 private:
    13     void dfs(int start, int len, vector<int> &nums, vector<int> &v, vector<vector<int> > &res, vector<bool> &visited) {
    14         if (start == len) {
    15             res.push_back(v);
    16             return ;
    17         }
    18         for (int i = 0; i < len; i++) {
    19             if (visited[i] == false) {
    20                 visited[i] = true;
    21                 v.push_back(nums[i]);
    22                 dfs(start + 1, len, nums, v, res, visited);
    23                 v.pop_back();
    24                 visited[i] = false;
    25             }
    26         }
    27     }
    28 };

    思路二:

     1 class Solution {
     2 public:
     3     vector<vector<int>> permute(vector<int>& nums) {
     4         sort(nums.begin(), nums.end());
     5         int len = nums.size();
     6         vector<vector<int> > res;
     7         dfs(0, len, nums, res);
     8         return res;
     9     }
    10 private:
    11     void dfs(int start, int len, vector<int> &nums, vector<vector<int> > &res) {
    12         if (start == len) {
    13             res.push_back(nums);
    14             return ;
    15         }
    16         for (int i = start; i < len; i++) {
    17             swap(nums[start], nums[i]);
    18             dfs(start + 1, len, nums, res);
    19             swap(nums[start], nums[i]);
    20         }
    21     }
    22 };
  • 相关阅读:
    总结PLSQL的快捷键以及使用技巧
    WebStorm 常用快捷键
    bootStrap小结3
    bootStrap小结2
    bootStrap小结1
    DataTable操作
    2017春 前端自动化(一)构建工具的搭建
    前端自动化之(一)—浏览器自动实时刷新
    基于div表单模拟右对齐
    纯css去实现loading动画效果图
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11543389.html
Copyright © 2020-2023  润新知