c_cpp 给定两个整数n和k,返回1 ... n中k个数的所有可能组合。例如,如果n = 4且k = 2,则解决方案是:

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 给定两个整数n和k,返回1 ... n中k个数的所有可能组合。例如,如果n = 4且k = 2,则解决方案是:相关的知识,希望对你有一定的参考价值。


void dfs(vector<int> &num, vector<vector<int>> &res, vector<int> comb, int curr_len, int K, int begin, int n) {
    if(curr_len == K) {
        res.push_back(comb);
        return;
    }
    for(int i=begin; i<n; i++) {
        //swap(num[i], num[begin]);                 // no need to swap anymore, since we handle combination not permutation. order does not matter!
        comb.push_back(num[i]);
        dfs(num, res, comb, curr_len+1, K, i+1, n); // gist, should be i+1 not begin+1 
        comb.pop_back();
        //swap(num[i], num[begin]);
    }
}
vector<vector<int>> get_combinations(vector<int> &num, int K) {
    vector<vector<int>> res;
    vector<int> comb;
    dfs(num, res, comb, 0, K, 0, num.size());
    return res;
}

int main() {
    vector<int> num = {1,2,3,4};
    vector<vector<int>> res = get_combinations(num, 2);
    for(auto a : res) {
        for(int d : a) cout << d << " ";
        cout << endl;
    }
}

以上是关于c_cpp 给定两个整数n和k,返回1 ... n中k个数的所有可能组合。例如,如果n = 4且k = 2,则解决方案是:的主要内容,如果未能解决你的问题,请参考以下文章