[LeetCode 216] Combination Sum III (Medium) dfs backtracking

  1. Combination Sum III
    finds all k combinations that add up to n. Only positive integers from 1 to 9 are allowed in the combination, and there are no repeated numbers in each combination.

Description:

All numbers are positive integers.
The solution set cannot contain repeated combinations.

示例 1:

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

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

Code:

class Solution {
    
    
public:
    vector<vector<int>> ans;
    vector<int> t;

    void dfs(int sum,int cnt,int k,int n)
    {
    
    
        if(sum>n || cnt>k) return; //剪枝

        if(sum==n && cnt==k) //和为n k个数 符合要求
        {
    
    
            ans.push_back(t);
            return;
        }

        for(int i=1;i<=9;i++)
        {
    
    
            if(!t.size() || t[t.size()-1]<i) //防止重复:后面数比前面大
            {
    
    
                t.push_back(i);
                dfs(sum+i,cnt+1,k,n);
                t.pop_back(); //回溯
            }
        }
    }

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

Guess you like

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