活跃农民
- 积分
- 431
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-7-28
- 最后登录
- 1970-1-1
|
参照大神点拔的八皇后思路。用bit manipulation 存状态 做了backtracking. 如下。大神的dp解更优。我这个可能稍微适合普通玩家理解一点。- #include <iostream>
- #include <vector>
- using namespace std;
- #define N 6 // N is the length of target string
- bool helper(vector<string>& strs, string target, int state, int pos){
-
- // calculate cross: indices of chars in target that also appear in strs[pos]. Those indices are set at the corresponding bit in "cross".
- if(state == (1 << N) - 1) return true; // all bits are set
- if(pos == N) return false; // already tried all strings in strs without success
-
- int cross = 0;
- string& curr = strs[pos];
- for(int i = 0; i < N; i++) {
- if(count(curr.begin(), curr.end(), target[i]))
- cross |= (1 << i);
- }
- int cand = cross & (~state);
- for(; cand != 0; cand -= cand & (-cand)) {
- if(helper(strs, target, state + (cand&(-cand)), pos+1)) return true;
- }
- return false;
- }
- bool makeTarget(vector<string>& strs, string target) {
- int state = 0;
- return helper(strs, target, state, 0);
- }
- int main(int argc, const char * argv[]) {
- // insert code here...
- vector<string> strs = {
- "abcdef",
- "abcdef",
- "abcdef",
- "abcdef",
- "abcdef",
- "abcdef"
- };
- cout << helper(strs, "abcdef", 0, 0) << endl;
-
- strs = vector<string> ({
- "abcdef",
- "abcdef",
- "abcdef",
- "abcdef",
- "abcdef"
- });
- cout << helper(strs, "abcdef", 0, 0) << endl;
-
- strs = vector<string> ({
- "axxxxx",
- "abyyyy",
- "abczzz",
- "abcdqq",
- "abcdep",
- "lllllf"
- });
- cout << helper(strs, "abcdef", 0, 0) << endl;
- return 0;
- }
复制代码 |
|