[leetcode] 216.Combination Sum III

来源:互联网 发布:windows wc命令 编辑:程序博客网 时间:2024/05/21 12:47

题目:

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.

Ensure that numbers within the set are sorted in ascending order.
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]]

题意:
找出所有的组合,包含k个数字,每个数字是在1-9之间,这k个数字之和是n。
思路:
采用回溯的方法进行查找所有组合。不过回溯的提前终止条件需要考虑。
比如还剩m个数字,m个数字最小必须从i开始,那么这m个数字的和的范围在[m * i + i * (i + 1)/2 ~ 9*m]之间,所以不满足这个条件就可以终止。
比如i是10了,那么也就可以终止了。
以上。
代码如下:

class Solution {public:    vector<vector<int>> combinationSum3(int k, int n) {        vector<vector<int>> result;        if(n < 1 || k < 1)return result;        vector<int> temp;        backTracking(0, result, n, k, 0, temp);    }    void backTracking(int last, vector<vector<int>> &result, int n, int k, int sum, vector<int> &temp) {        if(k == 0 && sum == n) {            result.push_back(temp);            return;        }        if(last == 9 ||             sum + last + 1 > n ||             (k * last + k * (k+1) /2 + sum) > n || (k * 9 + sum) < n)return;        else {            for(auto i = last + 1; i <= 9; i++) {                temp.push_back(i);                backTracking(i, result, n, k - 1, sum + i, temp);                temp.pop_back();            }        }    }};
0 0
原创粉丝点击