http://www.1point3acres.com/bbs/thread-184034-1-1.html
First Question:
A string consists of ‘0’, ‘1’ and '?'. The question mark can be either '0' or '1'. Find all possible combinations for a string.
01?0 output-->0100, 0110
First question This is very simple DFS:
#include <string> #include <vector> #include <iostream> using namespace std; void allCombinations(string str, int pos, vector<string>& res, string target) { if(target.size() == str.size()) { res.push_back(target); return; } for(int i = pos; i < str.size(); ++i) { if(str[i] == '?') { allCombinations(str, i+1, res, target + '0'); allCombinations(str, i+1, res, target + '1'); } else { allCombinations(str, i + 1, res, target + str[i]); } } } vector< string > allCombinations(string str) { bool exist = false; vector<string> res; for(int i = 0; i < str.size(); ++i) { if(str[i] == '?') {exist = true; break;} } if(exist == false) {res.push_back(str); return res; } else { allCombinations(str, 0, res, ""); return res; } } // a string only contains 0 and 1 and ? // substitute the ? with either 0 or 1 and return all possiblities. // for example: // 010?1 -> return 01001, 01011 int main(void) { vector<string> res = allCombinations("1?0?"); for(int i = 0; i < res.size(); ++i) { cout << res[i] << endl; } 1,1 Top
In this post, there is a very interesting posted. See this piece of code: This will cause repeating because of the bold line. I was first confused about where is the mistake. It is better to draw a graph to show the mistake.
public ArrayList<String> findCombination(String input) { ArrayList<String> res = new ArrayList<String>(); helper(res, 0, "", input); return res; } private void helper(ArrayList<String> res, int step, String cur, String input) { if(cur.length() == input.length()) { res.add(new String(cur)); return; } for(int i = step; i < input.length(); i++) { if(input.charAt(i) != '?') { <strong>cur += input.charAt(i);</strong> helper(res, i+1, cur, input); } else { helper(res, i+1, cur + "0", input); helper(res, i+1, cur + "1", input); } } }
A more elegant way to solve this confusion:
void allCombinations(string str, int pos, vector<string>& res, string target) { if(target.size() == str.size()) { res.push_back(target); return; } for(int i = pos; i < str.size(); ++i) { if(str[i] == '?') { allCombinations(str, i+1, res, target + '0'); allCombinations(str, i+1, res, target + '1'); } else { target = target + str[i]; // if it is not ?, the situation is confirmed. It doesn't need to go recursion. } } }