Purpose: Given a binary string as input, store strings resulting from toggling all 1's in the string to both 1 and 0 in all possible combinations.
Example Given a binary string "110", each "1" value can be switched to be either "1" or "0". "0" value must be left a "0" and order matters.
String 011 produces: [011, 010, 001, 000]
String 101 produces: [101, 100, 001, 000]
String 111 produces: [111, 110, 101, 100, 011, 010, 001, 000]
Problem I'm facing: My code doesn't store all possible combinations for each corresponding sub sequence when given the string "111".
Output of my code
Set:110 [110]
Set:011 [011, 010, 001, 000]
Set:000 [000]
Set:111 [111, 110, 101, 100, 011, 010, 001, 000]
Set:100 [100]
Set:001 [001, 000]
Set:101 [101, 100]
Set:010 [010]
Few examples where they are not storing all possible combinations into the hash: 010 (doesn't contain 000), 101 (doesn't contain 000 or 001).
111, 011, 001 all have correctly stored combinations when the function is originally given "111" as the input.
The code:
public static List<String> subsequence(char [] set, HashMap<String,List<String>> hs, int position){
List<String> listOfSubsequence = new ArrayList<String>();
// Dynamic programming part
if (hs.containsKey(String.valueOf(set))){
return hs.get(String.valueOf(set));
}
// base case
else if (position >= set.length ){
listOfSubsequence.add(String.valueOf(set));
hs.put(String.valueOf(set), listOfSubsequence);
return listOfSubsequence;
}
else if (set[position] == '0'){
return(subsequence(set,hs,position + 1));
}
else{
// Last situation where we have a 1 at position we're looking at
listOfSubsequence.addAll(subsequence(set,hs,position + 1));
set[position] = '0';
listOfSubsequence.addAll(subsequence(set,hs,position));
set[position] = '1';
hs.put(String.valueOf(set), listOfSubsequence);
return listOfSubsequence;
}
}