Saturday, November 15, 2014

[LeetCode] Permutation/Subset/DFS type of recursion

This post is dedicated to the type of question that ask you to enumerate a complete set or permutations. Problems such as 

  1. Given a collection of numbers, return all possible permutations.
  2. Given a collection of numbers that might contain duplicates, return all possible unique permutations.
  3. The set [1,2,3,…,n] contains a total of n! unique permutations. give n and k, return the kth permutation sequence.
  4. Given a set of distinct integers, S, return all possible subsets.
  5. Given a collection of integers that might contain duplicates, S, return all possible subsets.

First take a look at the first problem. permutations without duplicates.

The function should like

void permutation(vector &num, int index, vector<int>&tmp, vector<vector<int> >&res)

What it does is to take the index of num from 0 to n-1, iteratively swap index element with the element after it, then recursively call the function itself on index+1.

pseudo code:

void permutation(vector &num, int index, vector<int>&tmp, vector<vector<int> >&res){

}

No comments:

Post a Comment