티스토리 뷰
순열은 순서가 부여된 임의의 집합을 다른 순서로 뒤섞는 연산을 말한다.
1, 2, 3 이라는 숫자의 집합이 있을 때, 다음과 같이 뒤섞는 연산이다.
1,2,3
1,3,2
2,1,3
2,3,1
3,2,1
3,1,2
자바에서는 재귀연산을 이용해 해결할 수 있다.
기준점(pivot)이 되는 배열의 인덱스를 제공하면,
해당 인덱스의 뒤쪽에 있는 값들과 위치를 변경후 기준점을 다음의 위치로 옮겨 다시 호출하는 순서로 진행한다.
아래와 같이 배열을 이용하는 방법과 문자열을 이용하는 방법이 있다.
* 순열은 문자열의 길이이 따라 n! 로 시간이 걸리게 된다.
문자열의 길이가 20, 30 개가 된다면 시간이 굉장히 오래 걸리게 된다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Permutation { | |
public static void main(String[] args) { | |
int[] arr = { 1, 2, 3 }; | |
perm(arr, 0); | |
} | |
public static void perm(int[] arr, int pivot) { | |
if (pivot == arr.length) { | |
print(arr); | |
return; | |
} | |
for (int i = pivot; i < arr.length; i++) { | |
swap(arr, i, pivot); | |
perm(arr, pivot + 1); | |
swap(arr, i, pivot); | |
} | |
} | |
public static void swap(int[] arr, int i, int j) { | |
int temp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = temp; | |
} | |
public static void print(int[] arr) { | |
for (int i = 0; i < arr.length; i++) { | |
if (i == arr.length - 1) | |
System.out.println(arr[i]); | |
else | |
System.out.print(arr[i] + ","); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PermutationString { | |
public static void main(String[] args) { | |
permutation("abcd"); | |
} | |
public static void permutation(String str) { | |
permutation("", str); | |
} | |
private static void permutation(String prefix, String str) { | |
int n = str.length(); | |
if (n == 0) | |
System.out.println(prefix); | |
else { | |
for (int i = 0; i < n; i++) | |
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n)); | |
} | |
} | |
} |
http://gorakgarak.tistory.com/522
http://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string
반응형
'알고리즘' 카테고리의 다른 글
[스크랩] 나는 어떻게 알고리즘을 공부했을까? (1) | 2016.06.30 |
---|---|
[스크랩] 최대 연속 부분 구간 합 문제를 푸는 알고리즘 (0) | 2016.06.27 |
[스크랩] 문제 해결을 위한 창의적 알고리즘 (2) | 2016.06.24 |
[Java] 그래프 탐색법, 깊이우선탐색, 너비우선탐색 (0) | 2016.06.09 |
[JAVA] 버블정렬 (0) | 2016.06.08 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 파이썬
- HIVE
- S3
- airflow
- oozie
- error
- Linux
- AWS
- hbase
- 하둡
- yarn
- nodejs
- 백준
- emr
- SQL
- Hadoop
- ubuntu
- java
- mysql
- 정올
- 알고리즘
- Tez
- 다이나믹
- build
- Python
- 하이브
- SPARK
- bash
- HDFS
- 오류
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함