Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

示例 1:

  1. Input: nums = [1,2,3]
  2. Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

示例 2:

  1. Input: nums = [0,1]
  2. Output: [[0,1],[1,0]]

示例 3:

  1. Input: nums = [1]
  2. Output: [[1]]

提示:

  • 1 ≤ nums.length ≤ 6
  • -10 ≤ nums[i] ≤ 10
  • All the integers of nums are unique.

思路

本题可构建一棵树,如下图所示:
46-1.png

采用一次DFS即可得到答案。

DFS是基于递归,本题的终止条件是:当前层数等于输入列表的长度时,终止递归。

代码

  1. class Solution {
  2. public:
  3. void dfs(vector<int>& nums, vector< vector<int> >& ans, int level, bool visited[], vector<int>& path) {
  4. // 1. Exit condition
  5. if( nums.size() == level ) {
  6. ans.push_back( path );
  7. return;
  8. }
  9. // 2. Walk every node that not visited
  10. for(int i = 0; i < nums.size(); i++) {
  11. int node = nums[i];
  12. if( !visited[i] ) {
  13. visited[i] = true;
  14. path.push_back( node );
  15. dfs(nums, ans, level+1, visited, path);
  16. path.pop_back();
  17. visited[i] = false;
  18. }
  19. }
  20. }
  21. vector<vector<int>> permute(vector<int>& nums) {
  22. vector< vector<int> > answer;
  23. if( nums.size() == 0 ) return answer;
  24. if( nums.size() == 1 ) {
  25. answer.push_back(nums);
  26. return answer;
  27. }
  28. bool visited[ nums.size() ];
  29. for(int i = 0; i < nums.size(); i++)
  30. visited[i] = false;
  31. vector<int> path;
  32. dfs( nums, answer, 0, visited, path );
  33. return answer;
  34. }
  35. };