题目
链接:https://ac.nowcoder.com/acm/contest/3286/C
牛牛给你一个只包含字符1到9的字符串S, 你现在可以在任意两个数字字符之间插入’+'号构成一个式子,现在希望你能求出所有式子的结果之和。
NiuNiu gives you a string contains only digit characters ‘1’ to ‘9’, and tell you that you can insert a ‘+’ for any number of times between any two characters to form a formula. Now he wants to know the sum of the results of all the different formulas that can be formed.
输入描述:
输入只包含一个数字字符的字符串S(1≤∣S∣≤10)
The input is a string S only contains digit characters ‘1’ to ‘9’. (1≤∣S∣≤10)
输出描述:
输出总和
Print the sum.
示例1
输入
125
输出
176
说明
可以得到插入的结果:
125(不插入)
1 + 25 =26
12 + 5= 17
1 + 2 + 5 = 8
所以答案为: 125 + 26 + 17 + 8 = 176。
All the possible formulas:
125 (insert no ‘+’)
1 + 25 = 26
12 + 5 = 17
1 + 2 + 5 = 8
So the answer is 125 + 26 + 17 + 8 = 176.
示例2
输入
9999999999
输出
12656242944
DFS深度优先回溯算法
思路:
- 把输入的字符串input,转换为字符数组;
- 用回溯递归的方式,拼接字符串有两种选择,要么带
+
加号,要么不带+
加号; - 退出条件为,当字符数到倒数第二个数字的时候,手动拼接最后一个字符,放到结果列表中
resultList
。 - 遍历结果列表中
resultList
中的字符串,按照+
加号分割为数字字符串,把数字字符串转换为数字累加即可。
package backtracking;
import java.util.ArrayList;
import java.util.List;
public class AddPlusSymbol {
public static void main(String[] args) {
AddPlusSymbol obj = new AddPlusSymbol();
String input1 = "125";
Long result1 = obj.addPlus(input1);
System.out.println("input > " + input1 + " ; result > " + result1);
String input2 = "9999999999";
Long result2 = obj.addPlus(input2);
System.out.println("input > " + input2 + " ; result > " + result2);
}
public long addPlus(String input) {
if (input == null || input.length() == 0) {
return 0;
}
long result = 0;
List<String> resultList = new ArrayList<String>();
char[] chars = input.toCharArray();
// dfs
dfs(chars, resultList, "", 0);
// loop list sum
for (String s: resultList) {
String[] nums = s.split("\\+");
for (String n: nums) {
result += Long.parseLong(n);
}
}
return result;
}
private void dfs(char[] chars, List<String> resultList, String s, int start) {
// exit
if (start == chars.length - 1) {
resultList.add(s + chars[chars.length - 1]);
return;
}
s += chars[start];
dfs(chars, resultList, s + '+', start + 1);
dfs(chars, resultList, s, start + 1);
}
}