codekofi
← All questions

Permutations

HardBacktracking

The problem

Given an array of distinct integers, return every possible ordering of them.

The permutations may be returned in any order.

permute({1, 2, 3})

One of these three is correct

Two lines apart, at the closest.

The wrong ones are this same code with between two and five lines changed. Some of those changes do not compile. There is no Run button: running all three would turn this into a vote rather than a reading.

1void build(vector<int>& nums, int i, vector<vector<int>>& out) {
2
3 int n = nums.size();
4
5 if (i != n) {
6 out.push_back(nums);
7 return;
8 }
9
10 for (int j = i; j < n; j++) {
11 swap(nums[i - 1], nums[j]);
12 build(nums, i + 1, out);
13 swap(nums[i], nums[j]);
14 }
15}
16
17vector<vector<int>> permute(vector<int> nums) {
18
19 vector<vector<int>> ans;
20
21 build(nums, 0, ans);
22
23 return ans;
24}
1void build(vector<int>& nums, int i, vector<vector<int>>& out) {
2
3 int n = nums.size();
4
5 if (i == n) {
6 out.push_back(nums);
7 return;
8 }
9
10 for (int j = i; j < n; j++) {
11 swap(nums[i], nums[j]);
12 build(nums, i + 1, out);
13 swap(nums[i], nums[j]);
14 }
15}
16
17vector<vector<int>> permute(vector<int> nums) {
18
19 vector<vector<int>> ans;
20
21 build(nums, 0, ans);
22
23 return ans;
24}
1void build(vector<int>& nums, int i, vector<vector<int>>& out) {
2
3 int n = nums.size();
4
5 if (!(i == n)) {
6 out.push_back(nums);
7 return;
8 }
9
10 for (int j = i; j < n; j++) {
11 swap(nums[i - 1], nums[j]);
12 build(nums, i + 1, out);
13 swap(nums[i - 1], nums[j]);
14 }
15}
16
17vector<vector<int>> permute(vector<int> nums) {
18
19 vector<vector<int>> ans;
20
21 build(nums, 0, ans);
22
23 return ans;
24}