Permutations Problem


Description

LeetCode Problem 46.

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

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

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


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
    int n;
    vector<vector<int>> ans;
    
    void backtrack(int idx, vector<int>& nums) {
        if (idx == n) 
            ans.push_back(nums);
        
        int tmp;
        for (int i = idx; i < n; i ++) {
            tmp = nums[i];
            nums[i] = nums[idx];
            nums[idx] = tmp;
            
            backtrack(idx + 1, nums);
            
            tmp = nums[i];
            nums[i] = nums[idx];
            nums[idx] = tmp;
        }
    }
    
    vector<vector<int>> permute(vector<int>& nums) {
        n = nums.size();
        
        backtrack(0, nums);
        
        return ans;
    }
};




Related Posts

Unique Paths III Problem

LeetCode 980. You are given an m x n integer...

Split Array Into Fibonacci Sequence Problem

LeetCode 842. You are given a string of digits num,...

Partition To K Equal Sum Subsets Problem

LeetCode 698. Given an integer array nums and an integer...

Letter Case Permutation Problem

LeetCode 784. Given a string s, we can transform every...

24 Game Problem

LeetCode 679. You are given an integer array cards of...

Matchsticks To Square Problem

LeetCode 473. You are given an integer array matchsticks where...