递归——打印一个字符串的全部子序列


/*
 打印一个字符串的全部子序列
 子串:必须连续的
 abcd
 0: a, ab, abc, abcd
 1: b, bc, bcd
 2: c, cd
 3: d
  for
    for




子序列
原始序列中从左往右拿字符,可以不连续,要求相对次序不能变
    abc
                      ------------0------------
                  要a/                          \ 不要a
               -----1-----                  -----1-----
           要b/            \不要b        b要/            \b 不要
           -2-            -2-           -2-            -2-
      c要 /   \c不要   c要 /   \c不要 c要 /   \c不要   c要 /   \c不要
     abc     ab       ac      a      bc      b       c      ""
 */

func subs(str string) []string {
	var path string
	path = ""
	ans := &[]string{}
	process1(str,0,ans,path)
	return *ans
}

// str 固定不变
// index 此时来到的位置,要 or 不要
// ans 如果index 来到了 str 的终止位置,我要把我沿途路径所形成的的答案,放到ans里去
// 之前做出的选择,就是path
func process1(str string,index int, ans *[]string,path string)  {
	if index == len(str) {
		*ans = append(*ans,path)
		return
	}
	no := path
	process1(str, index + 1, ans, no)
	yes := path + string(str[index])
	process1(str, index + 1, ans, yes)
}

func TestSubStr(t *testing.T)  {
	fmt.Println(subs("abcdefg")) //也是深度优先遍历
}

/*
打印一个字符串的全部子序列,要求不要出现重复字面值的子序列
所有的字符都不是一样的
如aaaa

 */



func process2(str string,index int, ans map[string]bool,path string)  {
	if index == len(str) {
		ans[path] = true
		return
	}
	no := path
	process2(str, index + 1, ans, no)
	yes := path + string(str[index])
	process2(str, index + 1, ans, yes)
}

func subs2(str string) []string {
	var path string
	path = ""
	ans := map[string]bool{}
	process2(str,0,ans,path)

	result := []string{}

	for key, _ := range ans{
		result = append(result, key)
	}

	return result
}

func TestSubs2(t *testing.T)  {
	fmt.Println(subs2("aaaaa"))
}

/*
所有不同字面值的子序列的个数,动态规划
 */

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

metabit

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值