LeetCode 216. Combination Sum III

来源:互联网 发布:计算机文件搜索软件 编辑:程序博客网 时间:2024/05/22 10:42

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

分析:

深度优先搜索,数组存放,符合结果的存入vector中

class Solution {public:    vector<vector<int>> result;    int target;    vector<vector<int>> combinationSum3(int k, int n) {        int a[k];        target=n;        dfs(0,1,0,a,k);        return result;    }private:    void dfs(int cnt,int index,int sum,int *a,int k){        if((cnt==k&&sum!=target)||(cnt>k)||(sum>target)) return;        if(sum==target&&cnt==k){            vector<int>v;            for(int i=0;i<k;i++) v.push_back(a[i]);            result.push_back(v);            return;        }                for(int i=index;i<=9;i++){            a[cnt]=i;            dfs(cnt+1,i+1,sum+i,a,k);        }    }    };