/*
打印一个字符串的全部子序列
子串:必须连续的
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"))
}
/*
所有不同字面值的子序列的个数,动态规划
*/
递归——打印一个字符串的全部子序列
最新推荐文章于 2023-09-27 17:46:56 发布