Combinations

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:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
class Solution {
public:
    void dfs(vector<vector<int>> &ans, vector<int> path,int n, int k, int ok_n){
        if (ok_n == k){
            ans.push_back(path);
            return;
        }
        int i = 1;
        if (path.size() > 0){
            i = path[path.size() -1] + 1;
        }
        for(int j = i; j <= n; j++){
            path.resize(path.size() + 1);
            path[path.size() -1] = j;
            dfs(ans,path,n,k,ok_n + 1);
            path.resize(path.size() -1);    
        }
    }
    vector<vector<int> > combine(int n, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int>> ans;
        vector<int> path;
        dfs(ans,path,n,k,0);
        return ans;
    }
};

 

posted @ 2013-07-10 03:59  一只会思考的猪  阅读(177)  评论(0编辑  收藏  举报