Combinations Of String While Maintaining Order Of Words

前端 未结 3 1564
庸人自扰
庸人自扰 2021-01-24 20:17

Given a string:

String words = \"Mary had a little lamb\";

how to obtain a combination of sentence fragments while the order of occurrence of w

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-24 20:49

    Think about it this way:

    Mary <1> had <2> a <3> little <4> lamb
    

    Each of these s can be either true or false. If it is true, then you cut the sentence in that location.

    So, if you have n+1 words, your problem gets reduced to going through binary representation of numbers with n bit, that is from 0 to 2^n-1

    Examples:

    0110 -> {'Mary had', 'a', 'little lamb'}
    1111 -> {'Mary', 'had', 'a', 'little', 'lamb'}
    0001 -> {'Mary had a little', 'lamb'}
    1011 -> {'Mary', 'had a', 'little', 'lamb'}
    

提交回复
热议问题