【DFS + backtracking】LeetCode 216. Combination Sum III

Solution1:我的答案
DFS+backtracking,时间复杂度 O ( 2 m ) = O ( 2 9 ) ,空间复杂度 O ( k )

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int> > res;
        vector<int> temp;
        int start = 1;
        my_combinate(res, temp, n, k, start);
        return res;
    }

    void my_combinate(vector<vector<int> >& res, vector<int>& temp,
                      int n, int k, int start) {
        if (temp.size() == k) {
            if (n == 0) 
                res.push_back(temp);
            return;
        } else {
            for (int i = start; i <= 9; i++) {
                temp.push_back(i);
                my_combinate(res, temp, n - i, k, i + 1);
                temp.pop_back();
            }
        }
    }
};

猜你喜欢

转载自blog.csdn.net/allenlzcoder/article/details/81069952