Last active
June 2, 2022 06:33
-
-
Save chchwy/e277d140c49a066c170599c1298c87e0 to your computer and use it in GitHub Desktop.
Leetcode-216-combination-3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 216. Combination Sum III | |
// https://leetcode.com/problems/combination-sum-iii/ | |
class Solution { | |
public: | |
void backtrack(vector<int>& path, int next, int k, int n, vector<vector<int>>& combinations) { | |
if (path.size() == k) { | |
int sum = 0; | |
for (int i : path) { | |
sum += i; | |
} | |
if (sum == n) { | |
combinations.push_back(path); | |
} | |
} | |
for (int i = next; i <= 9; ++i) { | |
path.push_back(i); | |
backtrack(path, i + 1, k, n, combinations); | |
path.pop_back(); | |
} | |
} | |
vector<vector<int>> combinationSum3(int k, int n) { | |
vector<vector<int>> combinations; | |
// pick k numbers | |
// the sum is n | |
for (int i = 1; i <= (9 - k + 1); ++i) { | |
vector<int> path; | |
path.push_back(i); | |
backtrack(path, i + 1, k, n, combinations); | |
path.pop_back(); | |
} | |
return combinations; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 216. Combination Sum III | |
// https://leetcode.com/problems/combination-sum-iii/ | |
class Solution { | |
public: | |
void backtrack(vector<int>& path, int next, int k, int n, vector<vector<int>>& combinations) { | |
if (path.size() == k) { | |
int sum = 0; | |
for (int i : path) { | |
sum += i; | |
} | |
if (sum == n) { | |
combinations.push_back(path); | |
} | |
} | |
for (int i = next; i <= (9 - k + path.size() + 1); ++i) { | |
path.push_back(i); | |
backtrack(path, i + 1, k, n, combinations); | |
path.pop_back(); | |
} | |
} | |
vector<vector<int>> combinationSum3(int k, int n) { | |
vector<vector<int>> combinations; | |
// pick k numbers | |
// the sum is n | |
for (int i = 1; i <= (9 - k + 1); ++i) { | |
vector<int> path; | |
path.push_back(i); | |
backtrack(path, i + 1, k, n, combinations); | |
path.pop_back(); | |
} | |
return combinations; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment