Created
February 16, 2013 06:35
-
-
Save richzw/4965829 to your computer and use it in GitHub Desktop.
BackTrack
This file contains hidden or 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
| 排列的问题,求一个集合元素的全排列。 | |
| 整数集合s和一个整数sum,求集合s的所有子集su,使得su的元素之和为sum | |
| 1 #include <iostream> | |
| 2 | |
| 3 using namespace std; | |
| 4 | |
| 5 | |
| 6 int sum = 10; | |
| 7 int subsum = 0; | |
| 8 int s[5]= {1, 3, 6, 4, 2}; | |
| 9 int x[5]={0}; | |
| 10 int N = 5; | |
| 11 | |
| 12 void print(){ | |
| 13 for (int index = 0; index < N; ++index) | |
| 14 if (x[index] == 1) | |
| 15 cout << s[index] << " "; | |
| 16 cout << endl; | |
| 17 } | |
| 18 | |
| 19 void sumSet(int index){ | |
| 20 if (index >= N){ | |
| 21 if (sum == subsum) | |
| 22 print(); | |
| 23 return; | |
| 24 } | |
| 25 if (subsum < sum){ | |
| 26 x[index] = 1; | |
| 27 subsum += s[index]; | |
| 28 sumSet(index + 1); | |
| 29 subsum -= s[index]; | |
| 30 } | |
| 31 x[index] = 0; | |
| 32 sumSet(index + 1); | |
| 33 } | |
| 34 | |
| 35 int main(){ | |
| 36 sumSet(0); | |
| 37 | |
| 38 return 0; | |
| 39 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment