77. Combination

Insert picture description hereHere is a record of pruning.

i<=n-k+1

For example, n = 13, k = 4,

  • After selecting a number, the maximum i is 11, optional [11,12,13]
  • After choosing two numbers, the maximum i is 12, optional [12,13]
  • After choosing three numbers, the maximum i is 13, optional [13]

So there is no need to loop to n.
Here max (i) + select a few more numbers = n + 1
So, max (i) = n-1-select a few more numbers
We use k to select a few more numbers.

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>>ans;
        vector<int>tep;
        dfs(n,k,ans,tep,1);
        return ans;
    }
    void dfs(int n,int k,vector<vector<int>>& ans,vector<int> tep,int index){
        if(k==0){
            ans.push_back(tep);
            return;
        }
        for(int i=index;i<=n-k+1;i++){
            tep.push_back(i);
            dfs(n,k-1,ans,tep,i+1);
            tep.pop_back();
        }

    }
};
Published 161 original articles · Like 68 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/qq_43179428/article/details/105227983