题目一:【组合总和】力扣——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