46. Permutations

Posted mengchunchen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]
]


求数组的全排列


C++:
 1 class Solution {
 2 public:
 3     vector<vector<int>> permute(vector<int>& nums) {
 4         vector<vector<int>> permutes ;
 5         vector<int> permute ;
 6         vector<bool> visit(nums.size() , false) ;
 7         backtracking(nums,permutes,permute,visit) ;
 8         return permutes ;
 9     }
10     
11     void backtracking(vector<int>& nums ,vector<vector<int>>& permutes,vector<int>& permute,vector<bool>& visit){
12         if (permute.size() == nums.size()){
13             permutes.push_back(permute) ;
14             return ;
15         }
16         for(int i = 0 ; i < nums.size() ; i++){
17             if (visit[i]){
18                 continue ;
19             }
20             visit[i] = true ;
21             permute.push_back(nums[i]) ;
22             backtracking(nums,permutes,permute,visit) ;
23             permute.pop_back() ;
24             visit[i] = false ;
25         }
26     }
27 };

 







以上是关于46. Permutations的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode 46]全排列 Permutations 递归

白菜刷LeetCode记-46. Permutations

[Lintcode]15. Permutations/[Leetcode]46. Permutations

LeetCode 46. 全排列(Permutations)

LeetCode46,47 Permutations, Permutations II

leetcode 46-Permutations and 47-Permutations II