LeetCode—77. Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input:n = 4, k = 2Output:[  [2,4],  [3,4],  [2,3],  [1,2],  [1,3],  [1,4],]


给定n和k,要求列出n之内的所有的k个数的值比较。

递归,注意temp要设为静态变量。


vector> combine(int n, int k) {

        vector> res;

        vector temp;

        dfs(res, temp, n, k, 1);

        return res;

    }

    void dfs(vector>& res, vector& temp, int n, int k, int start){

        if(temp.size() == k){

            res.push_back(temp);

            return;

        }

        for(int i=start; i<=n; i++){

            temp.push_back(i);

            dfs(res, temp, n, k, i+1);

            temp.pop_back();

        }

    }

你可能感兴趣的:(LeetCode—77. Combinations)