Combinations

来源:互联网 发布:mac版photoshop cc2015 编辑:程序博客网 时间:2024/05/01 16:00

跟递归产生全排列一样一样的。

class Solution {public:    vector<vector<int> > combine(int n, int k) {        vector<vector<int>> res;        if (n == 0 || k == 0)            return res;        vector<int> used(n + 1, 0);        vector<int> path;        helper(k, 1, n, 1, res, path, used);        return res;    }    void helper(int k, int i, int n, int start, vector<vector<int>> &res, vector<int> &path, vector<int> &used) {        if (i == k + 1) {            res.push_back(path);            return;        }        for (int j = start; j <= n; ++j) {            if (used[j] == 0) {                used[j] = 1;                path.push_back(j);                helper(k, i + 1, n, j + 1, res, path, used);                path.pop_back();                used[j] = 0;            }        }    }};

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

0 0
原创粉丝点击