[LeetCode 77] Combination (medium) dfs backtracking

  1. Combination
    Given two integers n and k, return all possible combinations of k numbers in 1...n.
示例:

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Code:

class Solution {
    
    
public:
    vector<vector<int>> ans; //存答案
    vector<int> t;	//存过程

    void dfs(int n,int k,int index)
    {
    
    
        if(index==k) //t中有k个元素,就加入ans数组
        {
    
    
            ans.push_back(t);
            return;
        }

       for(int i=1;i<=n;i++)
       {
    
    
           if(!t.size() || i>t[t.size()-1]) //t为空 || 比最后一位大,才可以加入到t
           {
    
    
                t.push_back(i);
                dfs(n,k,index+1);
                t.pop_back(); //回溯
           }
       }
    }

    vector<vector<int>> combine(int n, int k) {
    
    
        dfs(n,k,0);
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45260385/article/details/108467480