Share my C++ solution,using DFS,easy to understand


  • 0
    V
    class Solution {
    public:
        vector<vector<int>> combine(int n, int k) {
            vector<vector<int>> ret;
            vector<int> temp;
            
            if (n < 1 || k < 1 || k > n)
                return ret;
                
            dfs(n, k, 1, ret, temp);
            
            return ret;
        }
        
        
        void dfs(int n, int k, int start, vector<vector<int>>& ret, vector<int> temp)
        {
            if (temp.size() == k)
            {
                ret.push_back(temp);
                return;
            }
    
            for (int i = start; i <=n; ++i)
            {
                temp.push_back(i);
                
                dfs(n, k, i+1, ret, temp);
                
                temp.pop_back();
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.