LeetCode 216 组合总和III HERODING的LeetCode之路

找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。

说明:

所有数字都是正整数。
解集不能包含重复的组合。 

示例 1:

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

示例 2:

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

解题思路:
这道题目相较于前两个组合题,难度可能还稍微降了一些,这道题限定了只能选1——9这9个数,而且不能有重复,思路依然是回溯剪枝,用一个深度优先算法就可以完成,注意这道题还要去重,map可以轻松解决,代码如下:

class Solution {
    
    
public:
    vector<vector<int>> combinationSum3(int k, int n) {
    
    
        vector<vector<int>> unique_ans;
        vector<vector<int>> ans;
        vector<int> res;
        dfs(k, n, ans, res, 1);
        map<vector<int>, int> Map;
        for(auto i : ans){
    
    
            Map[i] ++;
        }
        for(auto i : Map){
    
    
            unique_ans.emplace_back(i.first);
        }
        return unique_ans;
    }

    void dfs(int k, int n, vector<vector<int>>& ans, vector<int>& res,int index){
    
    
        if(index > 10){
    
    
            return;
        }
        if(k == 0 && n == 0){
    
    
            ans.emplace_back(res);
        }
        if(k == 0 && n != 0){
    
    
            return;
        }
        if(k != 0 && n == 0){
    
    
            return;
        }
        //不选择当前数
        dfs(k, n, ans, res, index + 1);
        //选择当前数
        if(n - index >= 0 && k > 0){
    
    
            res.emplace_back(index);
            dfs(k - 1, n - index, ans, res, index + 1);
            res.pop_back();
        }
    }
};

猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/108532621