Advertisement
Nickpips

C++ Permutations

Mar 8th, 2016
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. template<typename T>
  2. void permute( std::vector<T> nums, void (*function)( std::vector<T>& ), int length = -1 )
  3. {
  4. if( length < 0 || length > nums.size() )
  5. length = nums.size();
  6. std::function<void( int )> genPerms;
  7. std::vector<T> perm( length, 0 );
  8. std::vector<bool> used( length, false );
  9.  
  10. genPerms = [&function, &length, &nums, &perm, &used, &genPerms]( int n )
  11. {
  12. if( length == n )
  13. {
  14. function( perm );
  15. } else
  16. {
  17. for( int i = 0; i < nums.size(); i++ )
  18. {
  19. if( used[i] )
  20. continue;
  21. perm[n] = nums[i];
  22. used[i] = true;
  23. genPerms( n+1 );
  24. used[i] = false;
  25. }
  26. }
  27. };
  28.  
  29. genPerms( 0 );
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement