`

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);
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics