2019/11/05【组合总和】【终于做出来了】

题目一:【组合总和】力扣——39

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

所有数字(包括 target)都是正整数。
解集不能包含重复的组合。 
示例 1:

输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
  [7],
  [2,2,3]
]
示例 2:

输入: candidates = [2,3,5], target = 8,
所求解集为:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

#!/bin/bash
#组合总和
#author:yzt 2019-11-14
#
first_step(){
        zuheshu=`echo "$2"|sed 's#\[\|\]##g'|sed 's#,# #g'`
        first_nums=`cat tmp1.txt`
        cat /dev/null > tmp2.txt
        for i in $first_nums
        do
                for j in $zuheshu
                do
                        echo "$i+$j">>tmp2.txt
                done
        done
        cat /dev/null >tmp1.txt
        while read line
        do
                pk=`echo "$line"|bc`
                if [ $pk -eq $1 ];then
                        echo "$line" >>tmp3.txt
                elif [ $pk -lt $1 ];then
                        echo "$line">>tmp1.txt
                fi
        done < tmp2.txt
        cat /dev/null >tmp4.txt
         if [ ! -s tmp1.txt ];then
                content=`cat tmp3.txt|sed 's#^..##'|sed 's#+#,#g'`
                for i in $content
                do
                        echo "$i"|sed 's#,#\n#g'|sort|sed ":a;N;s/\n/,/g;ta" >>tmp4.txt
                done
                cat tmp4.txt |sort| uniq
                exit 0
        fi
        first_step "$target" "$shuzu1"
}
echo "0" > tmp1.txt
read -t 15 -p "请输入一个目标值:" target1
read -t 30 -p "请输入一组可使用的数组:" shuzu2
export target=`echo "$target1"|bc`
export shuzu1=$shuzu2
cat /dev/null > tmp3.txt
first_step "$target" "$shuzu1"

【脚本逻辑】

第一:这是需要通过“回溯和迭代”思想进行求解,简单来说就是从零开始不断使用数组中的元素相加,如下图所示:目标值为9,可使用数组为[2,3,4];解题的步骤如图中所画

第二步:在shell中使用迭代,不断对内容进行迭代,直到所有的数值均大于目标数值,则输出结果

【效果展示】

[root@localhost leetcode]# ./zuhezonghe.sh
请输入一个目标值:7
请输入一组可使用的数组:2,3,6,7
2,2,3
7
[root@localhost leetcode]# ./zuhezonghe.sh
请输入一个目标值:8
请输入一组可使用的数组:2,3,5
2,2,2,2
2,3,3
3,5
[root@localhost leetcode]# ./zuhezonghe.sh
请输入一个目标值:14
请输入一组可使用的数组:3,5,7,6
3,3,3,5
3,5,6
7,7

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值