• 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 };
  • 相关阅读:
    矩阵价值和
    排列组合问题
    X国的军队
    石子合并加强版
    P1042 乒乓球
    Dinner 点餐
    一文看尽图像分类问题
    [Udemy] Recommender Systems and Deep Learning in Python
    推荐系统学习
    [NLP] 酒店名归类
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11543389.html
Copyright © 2020-2023  润新知