Wednesday, August 2nd
It's perm time
Given an set of integers, return all possible permutations
The photo is licensed under the Create Commons Attribution-Share Alike 3.0 Unported license, courtesy of Wikipedia. One of the earliest perms
Generating permutations from a set of numbers follows the same backtracking approach as yesterday's combinations problem. In fact, by adding a single line, we can change finding combinations to permutations. We just add the if statement below, which tests whether or not a number to be added to the set has already appeared or not
if (find(curr.begin(), curr.end(), num) == curr.end()) {
...
}
This is fast and compact, but does require an additional linear scan through the data each time it's called.
A solution from vanAmsen swaps numbers around the array. Numbers are selected depending on an input index and switched with the value at the end of the array. Then the recursive function is called with the index incremented by 1. After the function returns, the numbers are swapped back.
swap(nums[begin], nums[i]);
permuteRec(nums, begin + 1, result);
swap(nums[begin], nums[i]);
The original solution with the if statement performed slightly faster, despite the additional scan
The problem taught 2 new functions, swap and find
Comments
Post a Comment