标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 7191 | Accepted: 3745 |
Description
Input
Output
Sample Input
4 6 4 3 2 2 1 1 5 3 2 1 1 400 12 50 50 50 50 50 50 25 25 25 25 25 25 0 0
Sample Output
Sums of 4: 4 3+1 2+2 2+1+1 Sums of 5: NONE Sums of 400: 50+50+50+50+50+50+25+25+25+25 50+50+50+50+50+25+25+25+25+25+25
Java AC 代码:
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { static int sum, number; static List<Integer> list ; //存放输入的数据 static List<Integer> path; //结果路径 static List<String> result;//存放结果路径的列表,每次得到结果时,都遍历该列表,看看是否有重复,不重复再往里添加 public static void main(String[] args) { Scanner sc = new Scanner(System.in); while((sum = sc.nextInt()) != 0 && (number = sc.nextInt()) != 0) { list = new ArrayList<Integer>(); path = new ArrayList<Integer>(); result = new ArrayList<String>(); for(int i = 0; i < number; i++) { list.add(sc.nextInt()); } for(int i = 0; i < number ; i++) { if(list.get(i) == sum) { //遍历的第一个数(i不一定是0)正好等于sum boolean flag = true; for(int j = 0; j < result.size(); j++) { //看结果列表里是否有相同的记过 if(Integer.toString(list.get(i)).equals(result.get(j))) { flag = false; break; } } if(flag) { result.add(Integer.toString(list.get(i))); //没有重复的 就添加进去 } } else { for(int j = i + 1; j < number; j++ ) { //i后的每一个数都可以作为第二个数进行遍历(这里应该可以把搜索范围缩小点) path.add(list.get(i)); dfs(list.get(i), j); path.remove(path.size() - 1); } } } System.out.println("Sums of " + sum + ":"); if(result.size() > 0){ for(int i = 0; i < result.size(); i++) { System.out.println(result.get(i)); } } else { System.out.println("NONE"); } } } public static void dfs(int currentSum, int currentLoc) { //参数是指当前的和 与当前输入列表中的位置 if(currentSum + list.get(currentLoc) == sum) { //得到结果 path.add(list.get(currentLoc)); String res = ""; for(int i = 0; i < path.size() - 1; i++) { res = res + Integer.toString(path.get(i)); res = res + "+"; } res = res + Integer.toString(path.get(path.size() - 1)); boolean flag = true; for(int i = 0; i < result.size(); i++) { //看结果列表里有没有和当前结果重复的 if(res.equals(result.get(i))) { flag = false; break; } } if(flag) { result.add(res); } path.remove(path.size() - 1); return; } if(currentSum + list.get(currentLoc) > sum) { return; } if(currentSum + list.get(currentLoc) < sum) { for(int i = currentLoc; i < number; i++) for(int j = i + 1; j < number; j ++) { path.add(list.get(i)); //这里开始把i写成了currentLoc,对于一些有重复数字的结果就会出错 dfs(currentSum + list.get(i), j); path.remove(path.size() - 1); } } } }
标签:
原文地址:http://www.cnblogs.com/kkkkkk/p/5535848.html