码迷,mamicode.com
首页 > 其他好文 > 详细

19.2.7 [LeetCode 46] Permutations

时间:2019-02-07 19:02:36      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:div   flag   void   lag   cli   ack   ble   display   开始   

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     void build(vector<bool>visited, vector<int>nums, vector<vector<int>>&ans,vector<int>now) {
 4         int flag = false;
 5         int n = nums.size();
 6         for(int i=0;i<n;i++)
 7             if (!visited[i]) {
 8                 visited[i] = true;
 9                 now.push_back(nums[i]);
10                 build(visited, nums, ans, now);
11                 visited[i] = false;
12                 now.pop_back();
13                 flag = true;
14             }
15         if (!flag)ans.push_back(now);
16     }
17     vector<vector<int>> permute(vector<int>& nums) {
18         vector<bool>visited(nums.size(), false);
19         vector<vector<int>>ans;
20         build(visited, nums, ans, vector<int>());
21         return ans;
22     }
23 };
View Code

一开始的暴力方法↑ 不出所料很慢

换了一种也没好多少

技术图片
 1 class Solution {
 2 public:
 3     vector<vector<int>> permute(vector<int>& nums) {
 4         vector<vector<int>>ans;
 5         ans.push_back(vector<int>(1, nums[0]));
 6         for (int i = 1; i < nums.size(); i++) {
 7             vector<vector<int>>tmp = ans;
 8             ans.clear();
 9             for (int j = 0; j < tmp.size(); j++) {
10                 vector<int>now = tmp[j];
11                 for (int k = 0; k <= now.size(); k++) {
12                     now.insert(now.begin() + k, nums[i]);
13                     ans.push_back(now);
14                     now.erase(now.begin() + k);
15                 }
16             }
17         }
18         return ans;
19     }
20 };
View Code

(算了算了

19.2.7 [LeetCode 46] Permutations

标签:div   flag   void   lag   cli   ack   ble   display   开始   

原文地址:https://www.cnblogs.com/yalphait/p/10354986.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!