LeetCode_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 {

private:

   vector<vector<int>> result;

   vector<int>  a ;

 public: 

   void findResult(int n, int k, int num,int start )

   {

      if(num == k)

       {

          result.push_back(a);

          return;

       }

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

       {

        

          a[num] = i;

          findResult( n,  k,  num+1, i+1);

        

       }

   }

    vector<vector<int> > combine(int n, int k) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

       

  

       a.resize(k);

       result.clear();

       findResult( n, k, 0, 1) ;

       return result;

     

    }

};

 重写后:

//Combinations

class Solution {

public:

    void DFS(int n, int start,int k, vector<int> &ans){

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

            res.push_back(ans);

            return;

        }

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

        {

            ans.push_back(i);

            DFS(n, i+1, k, ans);

            ans.pop_back();

        }

    }

    vector<vector<int> > combine(int n, int k) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        res.clear();

        vector<int> ans;

        DFS(n, 1, k, ans);

        return res;

        

    }

private:

    vector<vector<int>> res;

};

 

你可能感兴趣的:(LeetCode)