216. Combination Sum III

来源:互联网 发布:淘宝优惠劵是真的吗 编辑:程序博客网 时间:2024/05/22 16:45
class Solution {private:    vector<vector<int>> ans;    vector<int> s;public:    vector<vector<int>> combinationSum3(int k, int n) {        vector<bool> visited(10, false);        dfs(visited, 1, k, n);        return ans;    }        void dfs(vector<bool> &visited, int currentMin, int k, int n){        if(k < 0 || n < 0) return;        if(n == 0){            if(k == 0)                ans.push_back(vector<int>(s.begin(), s.end()));            return;        }        if(k == 0) return;        if(currentMin > 9)            return;                int minSelect, maxSelect;        (minSelect = n - (k-1)*9) > currentMin? : (minSelect = currentMin);        maxSelect = (n >= 9? 9 : n);                while(minSelect <= maxSelect){            if(visited[minSelect]){                ++minSelect;                continue;            }            s.push_back(minSelect);            visited[minSelect] = true;            dfs(visited, minSelect+1, k-1, n - minSelect);            s.pop_back();            visited[minSelect] = false;            ++minSelect;        }    }};

原创粉丝点击