LeetCode 216. 組合せ合計III(C++、python)


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]]

    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