LeetCode 216. Combination Sum III
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 216. Combination Sum III相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
leetcode [216]Combination Sum III
leetcode 216. Combination Sum III
Leetcode题解:L216/Combination Sum III
Leetcode 39 40 216 Combination Sum I II III