zoukankan      html  css  js  c++  java
  • 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;
    };
  • 相关阅读:
    github
    mysql安装和应用
    11月9日(visio安装很坑)
    11月4日
    11月3日
    10月29日
    10月26日
    10月25日
    9月29日
    9月28日
  • 原文地址:https://www.cnblogs.com/graph/p/3147504.html
Copyright © 2011-2022 走看看