N選M組合算法的非遞歸Java實現

組合算法:

這裏說的組合僅僅就是從1到N的N個數中選M個數的所有組合情況(N>=M),輸出格式按照數字的遞增順序輸出。

一般的代碼實現都是利用遞歸的思想,或者更具體說,是使用深度優先搜索思想來解決,寫法也比較簡潔明瞭。

今天就來用非遞歸的方式,解決一下這個經典問題。直接上代碼:

 

import java.util.Scanner;
import java.util.Stack;

public class DepthFirst {

	private static void printstack(Stack<Integer> stack) {
		if (stack == null) {
			return;
		}
		for (int i = 0; i < stack.size(); i++) {
			System.out.print(stack.get(i));
			if (i < stack.size() - 1) {
				System.out.print(" ");
			}
		}
		System.out.println();
	}

	private static void DFS(int n, int m) {
		Stack<Integer> stack = new Stack<>();
		stack.push(1);
		while (!stack.empty()) {
			if (stack.size() == m) {
				printstack(stack);
				int topVar = stack.peek();
				if (topVar + 1 <= n) {
					stack.pop();
					stack.push(topVar + 1);
				} else {
					stack.pop();
					if (stack.empty()) {
						return;
					}
					int sectopVar = stack.pop();
					stack.push(sectopVar + 1);
				}
			} else {
				int topVar = stack.peek();
				if (topVar + 1 <= n) {
					stack.push(topVar + 1);
				} else {
					stack.pop();
					if (stack.empty()) {
						return;
					}
					int sectopVar = stack.pop();
					stack.push(sectopVar + 1);
				}
			}
		}
	}

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNext()) {
			int n = scanner.nextInt();
			int m = scanner.nextInt();
			DFS(n, m);
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章