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;
        }
    }
};

 

posted on 2016-07-02 23:50  gavinXing  阅读(141)  评论(0编辑  收藏  举报