77. Combinations

problem description

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

algorithm thought

组合问题,典型的回溯法例题,使用回溯法解决

code

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> res;
        vector<int> tmp;
        helper(res,tmp,n,k,1);
        return res;
    }
    void helper(vector<vector<int>>& res,vector<int>&tmp,int n,int k,int pos){
        if(tmp.size()==k){
            res.push_back(tmp);
            return;
        }
        for(int i=pos;i<=n;++i){
            tmp.push_back(i);
            helper(res,tmp,n,k,i+1);
            tmp.pop_back();
        }
    }
};

algorithm analysis

组合问题需要放置k个值,每个值只能比后面的小,不能重复。时间复杂度不是太好分析,有很多种情况。但是回溯法时间复杂度一般都是O(2^n)

Last updated