Replace wild cards with all possible combinations of zeros and ones using recurs

 

Replace wild cards with all possible combinations of zeros and ones using recursion.

Input String: 0?1?

Output: 0010, 0011, 0110, 0111

 

Solution:

public List<String> replaceQuestionMark(String s) {
	List<String> result = new LinkedList<String>();
	replaceQuestionMarkRecursive(result, s.toCharArray(), 0);
	//System.out.println(Arrays.toString(result.toArray()));
	return result;
}

private void replaceQuestionMarkRecursive(List<String> result, char[] chars, int start) {
	if(start == chars.length) {
		result.add(new String(chars));
		return;
	}
	if(chars[start] == '?') {
		chars[start] = '0';
		replaceQuestionMarkRecursive(result, chars, start+1);
		chars[start] = '1';
		replaceQuestionMarkRecursive(result, chars, start+1);
		chars[start] = '?';
	} else {
		replaceQuestionMarkRecursive(result, chars, start+1);
	}
}

 

你可能感兴趣的:(LeetCode,String,Technical,interviews)