Monday, April 28, 2014

Combinations VS Permutation

Comination

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,
If n = 4 and k = 2, a solution is:
[
[1,2],
[1,3],
[1,4],
[2,4],
[2,3],
[3,4],
]


Solution

It's a way to simulate the process of getting 2 elements out of 4,
1. In round one, select 1 from 1...4 as the first number, you have [1]
2. next recursion, select one element from 2...n, you have [1,2], [1, 3], [1,4]
3 back to round one, select 2 from 2...4 as the first number, you have [2]
4. next recursion, select one element from 3..4, you have [2.3], [2,4]
......
vector<vector<int> > combine(int n, int k) {
vector<vector<int>> res;
vector<int> sol;
if(n<=0||k<=0||k>n){
res.push_back(sol);
return res;
}
combineRe(n,k,1,sol, res);
return res;
}
void combineRe(int n, int k, int level, vector<int> &sol, vector<vector<int>> &res){
if(sol.size() == k){
res.push_back(sol);
return;
}
for(int i=level; i<=n; i++){
sol.push_back(i);
combineRe(n, k, i+1, sol, res);
sol.pop_back();
}
}
view raw gistfile1.cpp hosted with ❤ by GitHub



Permutation

Get all permutations of a string


Solution

Swap the first element with all the other elements and permute on the rest of the string
void permutation(char[] s, int start, int end, vector<string> &res){
if(start == end){
string str(s);
res.push_back(str);
}
else{
for(int i= start; i<=end; i++){
swap(s, start, i);
permutation(s, start+1, end, res);
swap(s, start, i);
}
}
}
view raw gistfile1.cpp hosted with ❤ by GitHub

No comments:

Post a Comment