gistfile1.txt package com.test;import java.util.ArrayList;import java.util.List;public class Test1 { private static List list = new ArrayList();/** * 输入一个正数n,输出所有和为n连续正数序列 * @param n */public static voi
package com.test; import java.util.ArrayList; import java.util.List; public class Test1 { private static List> list = new ArrayList<>(); /** * 输入一个正数n,输出所有和为n连续正数序列 * @param n */ public static void jisuan(int n) { int start = 1; int end = 1; int sum = 1; while (start <= (n + 1) / 2) { if (sum < n) { end++; sum = sum + end; } if (sum > n) { sum = sum - start; start++; } if (sum == n) { for (int i = start; i <= end; i++) { System.out.print(i + " "); } System.out.println(); end++; sum = sum+end -start; start++; } } } /** * 输入一个正数n,输出所有和为n序列 * @param n */ public static void combiantion(int n) { int[] arr = createSortedArr(n); if (arr == null || arr.length == 0) { return; } List
list = new ArrayList(); for (int i = 1; i <= arr.length; i++) { combine(arr, 0, i, list); } jisuan(n); } private static void jisuan(int n) { // TODO Auto-generated method stub for(List list:Test.list){ Integer[] o = list.toArray(new Integer[list.size()]); if(sum(o)==n){ print(o); }; } } public static void print(Integer[] o){ if(o==null){ } for(int tmp:o){ System.out.print(tmp+" "); } System.out.println(); } public static int sum(Integer[] o){ int sum = 0; for(int tmp:o){ sum+=tmp; } return sum; } private static int[] createSortedArr(int n) { int[] a = new int[n]; int v = 1; for (int i = 0; i < n; i++) { a[i] = v; v++; } return a; } /** * <><><><><>><><><><><><> * @param cs * @param begin * @param number * @param list */ // 从字符数组中第begin个字符开始挑选number个字符加入list中 public static void combine(int[] cs, int begin, int number, List list) { if (number == 0) { Test.list.add(new ArrayList<>(list)); return; } if (begin == cs.length) { return; } list.add(cs[begin]); combine(cs, begin + 1, number - 1, list); list.remove((Integer)cs[begin]); combine(cs, begin + 1, number, list); } }