【leetcode】216. Combination Sum III

来源:互联网 发布:mac 系统怎么翻墙 编辑:程序博客网 时间:2024/06/06 00:37

一、题目描述

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.


Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]


Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]

思路:注意两个限制条件(1)个数为k个(2)k个数的范围都在[0, 9],使用回溯法。


c++代码(0ms,19.44%)

class Solution {public:    vector<vector<int> > res;    vector<int> ans;        void dfs(int start, int sum, int target, int k){        //start:初始值, sum当前和,target目标和,k个数        if(sum==target && k==0){            res.push_back(ans);            return;        }else if(sum>target)            return;        else{            for(int i=start; i<=target && i<=9; i++){               ans.push_back(i);               dfs(i+1, sum+i, target, k-1);               ans.pop_back();            }//for        }//else    }        vector<vector<int> > combinationSum3(int k, int n) {        if(k==0)            return res;        dfs(1, 0, n, k);        return res;    }};





0 0
原创粉丝点击