LeetCode 216. 组合总和 III(C++、python)

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

说明:

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

示例 1:

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

示例 2:

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

C++
 

class Solution {
public:
    void DFS(vector>& res, vector& tmp, vector nums, int k, int n, int w, int sum)
    {
        if(k==tmp.size() && n==sum)
        {
            res.push_back(tmp);
            return;
        }
        else if(sum>n || tmp.size()>k)
        {
            return;
        }
        for(int i=w;i> combinationSum3(int k, int n) 
    {
        vector> res;
        vector tmp;
        vector nums={1,2,3,4,5,6,7,8,9};
        int sum=0;
        DFS(res,tmp,nums,k,n,0,sum);
        return res;
    }
};

python

class Solution:
    def DFS(self, res, tmp, nums, k, n, w, su):
        if su==n and k==len(tmp):
            res.append(tmp.copy())
            return
        elif su>n or len(tmp)>k:
            return
        for i in range(w,len(nums)):
            su+=nums[i]
            tmp.append(nums[i])
            self.DFS(res,tmp,nums,k,n,i+1,su)
            del tmp[-1]
            su-=nums[i]

    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        res=[]
        tmp=[]
        su=0
        nums=[1,2,3,4,5,6,7,8,9]
        self.DFS(res,tmp,nums,k,n,0,su)
        return res

 

你可能感兴趣的:(LeetCode,回溯)