public class NumberPermutation {
public static void main(String[] args){
/*
* 123,132,213,231,312,321
*/
int[] numbers = new int[] {1,2,3};
backTrackPermutation(numbers ,0 ,2);
}
private static void backTrackPermutation(int[] numbers,int startIdx , int endIdx){
if(startIdx == endIdx){
printArray(numbers);
}else{
for(int j = startIdx; j <= endIdx ; j++){
swap(numbers, startIdx , j);
backTrackPermutation(numbers ,startIdx+1, endIdx);
swap(numbers, startIdx , j);
}
}
}
private static void swap(int[] numbers,int idx1 , int idx2){
int temp = numbers[idx1];
numbers[idx1] = numbers[idx2];
numbers[idx2] = temp;
}
private static void printArray(int[] numbers){
for(int i = 0 ; i < numbers.length ; i++){
System.out.print(numbers[i]);
}
System.out.println();
}
}
網頁
BloggerAds 廣告
標籤
- Java (96)
- Android (27)
- 演算法 (21)
- c++ (19)
- JavaScript (7)
- OpenMp (6)
- Design Pattern (4)
- 日文歌曲 (4)
- 資料結構 (4)
- Foundation Knowledge Of Programming (3)
- QUT (2)
- CodingHomeWork (1)
- Database (1)
- 英文歌詞 (1)
搜尋此網誌
2015年2月12日 星期四
回朔法(Backtracking)求所有數字的排列
2015年2月6日 星期五
用動態規劃演算法計算費波南西數列
動態規劃比遞迴寫法快好多.
public static void main(String[] args){
long start = System.currentTimeMillis();
System.out.println(new Fib().calFib(40));
long end = System.currentTimeMillis();
System.out.println("Dynamic Programming :" + (end - start) +" million seconds");
start = System.currentTimeMillis();
System.out.println(new Fib().recurFib(40));
end = System.currentTimeMillis();
System.out.println("Recurrence :" + (float)(end - start) +" million seconds");
}
int calFib(int toNumber){
int[] value = new int[100];
value[1] = 1;
for(int i = 1; i <= toNumber ; i++){
value[i+1] = value[i] + value[i-1];
}
return value[toNumber];
}
int recurFib(int toNumber){
if(toNumber == 0){
return 0;
}else if(toNumber == 1){
return 1;
}else{
toNumber -= 1;
return recurFib(toNumber)+recurFib(toNumber-1);
}
}
訂閱:
文章 (Atom)
我的網誌清單
標籤
日文歌曲
(4)
股市
(7)
股票
(9)
英文歌詞
(1)
時事
(1)
硬體(hardware)
(1)
資料結構
(4)
演算法
(21)
數學(Math)
(4)
ACM
(3)
ajax
(7)
algorithms
(1)
Android
(27)
Blog Notes(部落格記事)
(6)
C
(9)
c++
(19)
CodingHomeWork
(1)
Database
(1)
Design Pattern
(4)
Foundation Knowledge Of Programming
(3)
GWT
(1)
How
(2)
J2EE
(1)
Java
(96)
Java語言
(4)
JavaScript
(7)
Leetcode
(4)
LOL
(1)
OpenMp
(6)
QUT
(2)
Uva
(2)
Yahoo知識問答
(11)