码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 216. Combination Sum III

时间:2016-07-03 00:27:31      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

Problem: https://leetcode.com/problems/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.

 

Thought:

Single backtracking

 

Code C++:

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> solution;
        if (k <= 0 || k > 9 || n <= 0 || n > 45) {
            return solution;
        }
        if (k == 1) {
            if (n >= 1 && n <= 9) {
                vector<int> solve;
                solve.push_back(n);
                solution.push_back(solve);
                return solution;
            } else
                return solution;
        }
        
        vector<int> solve;
        bfs(solution, solve, k, n, 0);
        return solution;
    }
    
    void bfs(vector<vector<int>> &solution,vector<int> &solve, int k, int n, int circle){
        if (circle == k - 1) {
            int sum = 0;
            for (int i = 0; i < solve.size(); i++) {
                sum += solve[i];
            }
            int last = n - sum;
            if (last > solve[circle - 1] && last<= 9) {
                solve[circle] = last;
                solution.push_back(solve);
                return;
            }
            return;
        }
        
        if (circle == 0) {
            vector<int> solve(k, 0);
            for (int i = 1; i <= 9; i++) {
                solve[circle] = i;
                bfs(solution, solve, k, n, circle + 1);
                solve[circle + 1] = 0;
            }
            return;
        } else {
            for (int i = solve[circle - 1] + 1; i <= 9; i++) {
                solve[circle] = i;
                bfs(solution, solve, k, n, circle + 1);
                solve[circle + 1] = 0;
            }
            return;
        }
    }
};

 

LeetCode 216. Combination Sum III

标签:

原文地址:http://www.cnblogs.com/gavinxing/p/5636342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!