Combinations (枚举1到n中k个数)【leetcode】

n个数取k个值,枚举所有取法。

dfs记忆搜索,dep代表枚举到第几个值,p表示当前枚举的值的最小值。


vector<vector<int>> ha;
vector<int> v;
class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        ha.clear();
        v.clear();
        v.resize(k);
        hehe(1,0,k,n);
        return ha;
    }
    
    void hehe(int p,int dep,int k,int n)
    {
        if(dep==k)
        {
            ha.push_back(v);
            return ;
        }
        
        for(int i=p;i<=n;++i)
        {
            v[dep]=i;
            hehe(i+1,dep+1,k,n);
        }
        
    }
};


你可能感兴趣的:(LeetCode,搜索,DFS,combinations)