logseq_notes/pages/OJ notes/pages/Leetcode Permutations.md
2023-06-14 14:27:22 +08:00

1.8 KiB

Leetcode Permutations

2022-07-20 14:16

Algorithms:

#algorithm #backtrack

Difficulty:

#coding_problems #difficulty_medium

Additional tags:

#leetcode

Revisions:

N/A

Problem

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

Examples

Example 1:

**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:

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

Example 3:

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

Constraints

Constraints:

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

Thoughts

[!summary] This is a #backtrack problem

Backtrack problem, see alse Leetcode Combinations

Solution

class Solution {
void backtrack(vector<vector<int>> &ans, vector<int> &combs, bool unused[],
               vector<int> &nums, int n, int k) {
  // if the end is hit, append it to ans.
  if (k == 0) {
    ans.push_back(combs);
  } else {
    // iterate over the unused vector
    for (int i = 0; i < n; i++) {
      if (!unused[i]) {
        continue;
      }
      unused[i] = false;
      combs.push_back(nums[i]);

      backtrack(ans, combs, unused, nums, n, k - 1);

      combs.pop_back();
      unused[i] = true;
    }
  }
}

public:
vector<vector<int>> permute(vector<int> &nums) {
  // This can be modified from combinations
  vector<vector<int>> ans = {};
  vector<int> combs = {};
  int size = nums.size();

  bool unused[size];
  for (int i = 0; i < size; i++) {
    unused[i] = true;
  }

  backtrack(ans, combs, unused, nums, size, size);
  return ans;
}
};