LeetCode OJ:Combinations

Combinations

 

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

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

递归:


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

迭代:

class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        vector<int> values(n);
        iota(values.begin(),values.end(),1);
        
        vector<bool> select(n,false);
        fill_n(select.begin(),k,true);
        
        vector<vector<int>> result;
        do{
            vector<int> one(k);
            for(int i=0,index=0;i<n;++i)
                if(select[i])
                    one[index++]=values[i];
            result.push_back(one);
        }while(prev_permutation(select.begin(),select.end()));
        return result;
    }
};


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