2017-04-02 7 views
1

그래, 우리는 기본적으로 대답하기 위해이 질문을하지만, 나는 매우 혼란스럽고 모든 가능한 조합을 얻기 위해 재귀를 사용하는 법을 모르겠다. 누군가 나를 구 해주십시오! , 그리고 ArrayLists의 설정을 반환자바에서 집합의 가능한 모든 조합을 찾을 수

소요 (이 설정을 변경하지 않아야 코드 사용 가능한 비드 colours를 나타내는)와 Strings의 세트 (각 목걸이에 구슬의 수를 나타내는)를 int npublic static method threadings, 쓰기 Strings은 주어진 색상의 n 개의 비드가 스레드 될 수있는 모든 순서를 나타냅니다. n < 1의 경우, 하늘의 값이 1, 공백 인 ArrayList를 포함한 Set를 돌려줍니다.

threadings(1, {red,green}) = {[red],[green]}

threadings(2, {red,green}) = {[red,red],[red,green],[green,red],[green,green]}

threadings(3, {red}) = {[red,red,red]} • 힌트 • threadings(0, {red,green}) = {[]} • : 올바른 행동

예를 들면 당신은 아마 원할 것입니다 threadings는하지만, 자신을 재귀 적으로 호출 올바른 방법으로 전체 표시를 사용할 수 있습니다.

내가 지금까지 쓴 것입니다 :

public static HashSet<ArrayList<String>> threadings (int n, Set<String> colours){ 
    HashSet<ArrayList<String>> result= new HashSet<ArrayList<String>>(); 
    ArrayList<String> inresult= new ArrayList<String>(); 
    String[] col= new String[colours.size()]; 
    if (n==0){ 
     result.add(inresult); 
     return result; 
    }else{ 

    } 
} 
+0

가 [구글에 신속하게 발견.] (http://www.geeksforgeeks.org/print- 주어진 배열 배열 내에서 가능한 모든 요소의 조합 – Moira

+0

또는 stackoverflow : http://stackoverflow.com/a/42911720/5057029 – DontPanic

+0

참조 [this ] (http://stackoverflow.com/questions/7218923/possible-combinations-of-a-list) 질문. 세트 작업은 비슷합니다 –

답변

0

이 시도 :

public static HashSet<ArrayList<String>> threadings (int n, Set<String> colours) { 
    List<String> colorsList = new ArrayList<>(colours); 
    ArrayList<String> resultList = new ArrayList<>(); 
    HashSet<ArrayList<String>> result = new HashSet<ArrayList<String>>(); 
    int carry; 
    int[] indices = new int[n]; 
    do 
    { 
     for(int index : indices) { 
      resultList.add(colorsList.get(index)); 
     } 
     result.add(resultList); 
     resultList = new ArrayList<>(); 

     carry = 1; 
     for(int i = indices.length - 1; i >= 0; i--) 
     { 
      if(carry == 0) 
       break; 

      indices[i] += carry; 
      carry = 0; 

      if(indices[i] == colorsList.size()) 
      { 
       carry = 1; 
       indices[i] = 0; 
      } 
     } 
    } 
    while(carry != 1); 

    return result; 
}