2015年9月12日星期六

Lintcode: Combination

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Have you met this question in a real interview? 
Yes
Example
For example,
If n = 4 and k = 2, a solution is:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]
Tags Expand 


Reference:
//thought
//codes

DFS  recursively  -- backtracking problem
Time: O(n!)   -- also worst case
Space: O(k)  ---- longest depth is k  ---- Worst case O(n)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
    /**
     * @param n: Given the range of numbers
     * @param k: Given the numbers of combinations
     * @return: All the combinations of k numbers out of 1..n
     */
    vector<vector<int> > combine(int n, int k) {
        // write your code here
        vector<int> tempres;
        vector<vector<int> >res;
        DFS(1, n, k, tempres, res);
        return res;
    }
    void DFS(int start, int n, int k, vector<int> &tempres, vector<vector<int> > &res){
        if(k == 0) {
            res.push_back(tempres);
            return;
        }

        for(int i = start; i <= n; i++){
            tempres.push_back(i);
            DFS(i+1, n, k-1, tempres, res);
            tempres.pop_back();
        }
    }
};


没有评论:

发表评论