创建一组字符子集的最佳解决方案是什么?
时间:2020-03-05 18:47:31 来源:igfitidea点击:
我知道"最佳"是主观的,因此根据说法,以下问题的最佳解决方案是什么:
给定一个长度为n的字符串(例如" abc"),生成该字符串的所有适当子集。因此,对于我们的示例,输出将为{},{a},{b},{c},{ab},{bc},{ac}。 {abc}。
你怎么认为?
解决方案
回答
def subsets(s): r = [] a = [False] * len(s) while True: r.append("".join([s[i] for i in range(len(s)) if a[i]])) j = 0 while a[j]: a[j] = False j += 1 if j >= len(s): return r a[j] = True print subsets("abc")
回答
我们需要电源。它可以递归和归纳计算。 ;-)
回答
请原谅伪代码...
int i = 0; Results.push({}); While(i > Inset.Length) { Foreach(Set s in Results) { If(s.Length == i) { Foreach(character c in inSet) Results.push(s+c); } i++; }
回答
递归方法-" abc"的子集有两种类型:那些是" bc"的子集,以及那些是" a"加" bc"的子集。因此,如果我们知道" bc"的子集,那很容易。
或者,长度为n的字符串具有2 ^ n个子集。因此,编写两个嵌套循环:i从0到2 ^ n -1计数(对于子集),j从0到n-1计数(对于第i个子集中的字符)。当且仅当i的第j位为1时,输出字符串的第j个字符。
(好吧,我们确实说过"最佳"是主观的……)
回答
以二进制表示形式解释一个数字,以指示子集中包含哪些元素。假设集合中有3个元素。数字4对应二进制表示法的0100,因此我们将其解释为大小1的子集,仅包含第二个元素。这样,生成所有子集的计数高达(2 ^ n)-1
char str [] = "abc"; int n = strlen(str); // n is number of elements in your set for(int i=0; i< (1 << n); i++) { // (1 << n) is equal to 2^n for(int j=0; j<n; j++) { // For each element in the set if((i & (1 << j)) > 0) { // Check if it's included in this subset. (1 << j) sets the jth bit cout << str[j]; } } cout << endl; }