Leetcode: Combinations

来源:互联网 发布:毛概网络课程答案 编辑:程序博客网 时间:2024/05/18 18:21

http://oj.leetcode.com/problems/combinations/


class Solution {private:    vector<bool> used;    vector<vector<int> > res;    vector<int> current;public:    // It asks for all the combinations, so we need the variable last to avoid duplications    void DFS(int n, int k, int depth, int last=-1){        if(depth==k){            res.push_back(current);        }        else{            for(int i=last+1;i<n;i++){                if(used[i]==false){                    current[depth]=i+1;                    used[i]=true;                    DFS(n, k, depth+1, i);                    used[i]=false;                }            }        }    }    vector<vector<int> > combine(int n, int k) {        used.clear();        res.clear();        current.clear();        if(k==0) return res;        for(int i=0;i<n;i++) used.push_back(false);        for(int i=0;i<k;i++) current.push_back(0);        DFS(n, k, 0);        return res;    }};


原创粉丝点击