LeetCode-216 Combination Sum III

题目描述

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

题目大意

给定k和n,要求用k个不重复的1-9的数字,组成相加之和为n的集合,将所有可能的集合返回。

示例

E1

Input: k = 3, n = 7
Output: [[1,2,4]]

E2

Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]

解题思路

因为数字集合由不同的1-9的数字组成,因此不同的组合情况不会太多,可以DFS遍历所有可能的组合情况,将符合条件的数组记录到结果当中。

复杂度分析

时间复杂度:O(N)

空间复杂度:O(N)

代码

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int> > res;
        vector<int> tmp;
        //若输入为不可能出现的结果或非法输入,则返回空集
        if(k > 9 || (n == 0 && k != 0) || (n != 0 && k == 0)) {
            return res;
        }
        
        dfs(res, tmp, 1, k, n);
        
        return res;
    }
    
    void dfs(vector<vector<int> >& res, vector<int>& com, int s, int k, int n) {
        //若k和n同时为0,则代表当前保存的组合情况符条件,将其保存到结果集当中
        if(!k && !n)
            res.push_back(com);
        //依次遍历1-9的组合情况,每次起始数字都随着递归以此增加,查询符合条件的结 
        //
        for(int i = s; i < 10; ++i) {
            //若该数字可以放入集合当中
            if(i <= n) {
                com.push_back(i);
                dfs(res, com, i + 1, k - 1, n - i);
                com.pop_back();
            }
            else
                break;
        }
    }
};
原文地址:https://www.cnblogs.com/heyn1/p/11058470.html