`

给一个参数n,求这个数的所有整数求和排列,不允许有重复

阅读更多
给一个参数n,求这个数的所有整数求和排列,不允许有重复

简单解答,算法还有优化空间


public static void main(String[] args) {
		int n = 10;
		
		int[] pre = new int [(int)Math.sqrt(2 * n)];
		
		p1(n, 1, pre, 0);
		
	}
	
	public static void p1 (int n, int start, int[] pre, int index) {
		int current = 0;
		for (int j = 0; j < index; j ++) {
			current += pre[j];
		}
		
		int r = n - current;
		
		int max = r % 2 == 0 ? r / 2 - 1 : r / 2;
		
		if (start > max) return;
		
		for (int i = start; i < max; i ++) {
			for (int j = 0; j < index; j ++) {
				System.out.print(pre[j] + "  ");
			}
			
			System.out.println(i + "  " + (r - i));

			pre[index] = i;
			
			p1(n, i + 1, pre, index + 1);
		}
		
		for (int j = 0; j < index; j ++) {
			System.out.print(pre[j] + "  ");
		}
		
		System.out.println(max + "  " + (r - max));
	}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics