天天看點

題目:有1、2、3、4個數字,能組成多少個互不相同且無重複數字的三位數?都是多少?

public static void main(String[] args) {
		Set<String> numberList = new HashSet<String>();
		for (int i = 1; i <= 4; i++) {
			getNumber(numberList, i + "");
		}
		List<String> numbers = new ArrayList<String>(numberList);
		Collections.sort(numbers);
		System.out.println(numbers);
		System.out.println(numbers.size());
	}

	private static void getNumber(Set<String> numberList, String first) {
		String second;
		String third;
		second = "";
		third = "";
		for (int i = 1; i <= 4; i++) {
			second = "" + i;
			if (second.equals(first))
				continue;

			for (int j = 1; j <= 4; j++) {
				third = "" + j;
				if (third.equals(first))
					continue;

				if (!second.equals(third)) {
					numberList.add(first + second + third);
				}
			}
		}
	}
           
</pre><pre name="code" class="java">閑着沒有事情做就刷刷簡單的題目,額,自己的實作比較麻煩啊。看了一下别人的實作還是很簡單的。
           
比較标準的答案:
           
<pre name="code" class="java">	public static void main(String[] args) {
		int i = 0;
		int j = 0;
		int k = 0;
		int t = 0;
		for (i = 1; i <= 4; i++)
			for (j = 1; j <= 4; j++)
				for (k = 1; k <= 4; k++)
					if (i != j && j != k && i != k) {
						t += 1;
						System.out.println(i * 100 + j * 10 + k);
					}
		System.out.println(t);
	}
           
總結:自己體會到的就是不管多簡單,也要自己試試,很可能收獲了另一種思維。
           
還有就是沒有經過思考的東西比較容易忘記。遇到了先自己思考,自己應該如何做,然後在參考别人的做法。
           
</pre><pre name="code" class="java">
           

繼續閱讀