• LeetCode46,47 Permutations, Permutations II


    题目:

    LeetCode46 I

    Given a collection of distinct numbers, return all possible permutations. (Medium)

    For example,
    [1,2,3] have the following permutations:

    [
      [1,2,3],
      [1,3,2],
      [2,1,3],
      [2,3,1],
      [3,1,2],
      [3,2,1]
    ]

    LeetCode47 II

    Given a collection of numbers that might contain duplicates, return all possible unique permutations.(Medium)

    For example,
    [1,1,2] have the following unique permutations:

    [
      [1,1,2],
      [1,2,1],
      [2,1,1]
    ]
    

     分析: 首先先用next_permutation解这两个题。用好STL。

    Permutations I:

     1 class Solution {
     2 public:
     3     vector<vector<int>> permute(vector<int>& nums) {
     4         vector<vector<int>> result;
     5         int len = nums.size();
     6         sort(nums.begin(), nums.end());
     7         do {
     8             result.push_back(nums);
     9         } while (next_permutation(nums.begin(),nums.end()));
    10     
    11         return result;
    12     }
    13 };

    Permutations II:

     1 class Solution {
     2 public:
     3     vector<vector<int>> permuteUnique(vector<int>& nums) {
     4         vector<vector<int>> result;
     5         int len = nums.size();
     6         sort(nums.begin(), nums.end());
     7         do {
     8             result.push_back(nums);
     9         } while (next_permutation(nums.begin(),nums.end()));
    10     
    11         return result;
    12     }
    13 };

    当然,用STL写好的函数肯定不是面试的目的,permutation的递归方法也是经典的回溯算法题。

    代码:

     1 class Solution {
     2 private:
     3     vector<vector<int>> result;
     4     void helper(vector<int>& nums, int start, int end) {
     5         if (start == end) {
     6             result.push_back(nums);
     7         }
     8         for (int i = start; i <= end; ++i) {
     9             swap(nums[start], nums[i]);
    10             helper(nums, start + 1, end);
    11             swap(nums[start], nums[i]);
    12         }
    13     }
    14 public:
    15     vector<vector<int>> permute(vector<int>& nums) {
    16         helper(nums, 0, nums.size() - 1);
    17         return result;
    18     }
    19 };
  • 相关阅读:
    分别针对Customers表与Order表的通用查询操作
    类的继承
    kubernetes service 原理解析
    k8s生命周期-钩子函数
    深入理解Pod-初始化容器
    为 Pod 或容器配置安全性上下文
    Docker四种网络模式
    python中__new__方法详解及使用
    浅析python析构函数
    k8s中的网络
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5843945.html
Copyright © 2020-2023  润新知