zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    去过的论坛重新注册了
    for … in … 语句的使用
    删除整个目录
    使用Live Writer测试 1
    Google ProtocolBuffer.net简介与使用
    linq to sql 系列之 linq to sql性能优化技巧
    单元测试之道(使用NUnit)
    提高软件测试能力的19条建议
    System.Runtime.Caching;
    EneityFramework+DomainDataSource+Silverlight完成数据读取分页排序与修改
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5843945.html
Copyright © 2011-2022 走看看