首页 > 其他 > 详细

Permutations

时间:2015-10-13 06:57:48      阅读:354      评论:0      收藏:0      [点我收藏+]

Given a collection of numbers, return all possible permutations.

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

 

Analyse: 

    (1) Swap the 1st element with all the elements, including itself.
       (2) Then the 1st element is fixed, go to the next element.
       (3) Until the last element is fixed. Output.

技术分享

Runtime: 16ms

 1 class Solution {
 2 public:
 3     vector<vector<int>> permute(vector<int>& nums) {
 4         vector<vector<int> > result;
 5         if(nums.empty()) return result;
 6         
 7         helper(result, nums, 0, nums.size() - 1);
 8         return result;
 9     }
10     
11     void helper(vector<vector<int> >& result, vector<int> nums, int depth, int n){
12         if(depth == n){
13             result.push_back(nums);
14             return;
15         }
16         for(int i = depth; i < nums.size(); i++){
17             swap(nums[depth], nums[i]);
18             helper(result, nums, depth + 1, n);
19             swap(nums[depth], nums[i]);
20         }
21     }
22 };

 

Permutations

原文:http://www.cnblogs.com/amazingzoe/p/4873385.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!