Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
039. Combination Sum (Medium) link :
Title: https://leetcode.com/problems/combination-sum/
Code (GitHub): Https://github.com/illuz/leetcode :
Give a set of positive integers, and a target number, select some number from the set so that their sum equals the target number, and you can repeat the selection of the number in the collection.
The resulting set of solutions cannot have duplicates. Analysis :
The violent search used to be able, first row, and then with DFS, each time there are two choices, one is to select the current number and then recursive current number, and the second is not the current number of direct recursion number.
This is a good thing to understand about DFS. code : (c + +)
* * * Author:illuz <iilluzen[at]gmail.com> * file:ac_dfs_n!. CPP * Create date:2015-01-01 10:45:58 * Descripton:dfs, choose or not choose */#include <bits/stdc++.h> usin
G namespace Std;
const int N = 0;
Class Solution {private:void dfs (vector<vector<int> > &ans, vector<int> &single,
vector<int> &candi, int cur, int rest) {int sz = candi.size ();
if (sz <= cur | | Rest < 0) return;
if (rest = 0) {ans.push_back (single);
Return
}//Choose cur single.push_back (candi[cur]);
DFS (ans, single, Candi, cur, rest-candi[cur]);
Single.pop_back ();
Don ' t choose Cur dfs (ans, single, Candi, cur + 1, rest); public:vector<vector<int> > Combinationsum (vector<int> &candidates, int target) {VEC
tor<vector<int> > ans; Vector<int&gT
Single
Sort (Candidates.begin (), Candidates.end ());
DFS (ans, single, candidates, 0, target);
return ans;
}
};
int main () {int tar;
int n;
Solution s;
CIN >> n >> Tar;
Vector<int> v (n);
for (int i = 0; i < n; i++) cin >> V[i];
vector<vector<int> > Res = s.combinationsum (v, tar);
for (auto &i:res) {for (auto &j:i) cout << J << ";
Puts ("");
return 0; }