77. Combinations

image.png

典型的dfs+回溯

class Solution {
public:
    vector> combine(int n, int k) {
        vector> result;
        vector list;
        if(n == 0) return result;
        dfs(n, k, 1, result, list);
        return result;
    }
private:
    void dfs(int n, int k, int cur, vector>& result, vector list){
        if(list.size()== k) result.push_back(list);
        for(int i = cur; i <= n; i++){
            list.push_back(i);
            dfs(n, k, i+1, result, list);
            list.pop_back();
        }
    }
};

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