Skip to content

Instantly share code, notes, and snippets.

@WeiChienHsu
Created February 2, 2019 15:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WeiChienHsu/717a6dece259e410e9bab0e1d9d6e025 to your computer and use it in GitHub Desktop.
Save WeiChienHsu/717a6dece259e410e9bab0e1d9d6e025 to your computer and use it in GitHub Desktop.
Permutation Problem
import java.util.*;
class Permutation {
public static void main(String[] args) {
String[] dayHoursList = new String[]{"4", "4", "4", "4", "4", "?", "?"};
int maxDayHours = 8;
int weekHours = 28;
List<String> results = getPermutation(dayHoursList, maxDayHours, weekHours);
for(int i = 0; i < results.size(); i++) {
System.out.println(results.get(i));
}
}
public static List<String> getPermutation(String[] dayHoursList, int maxDayHours, int weekHours) {
List<String> results = new ArrayList<>();
int permutationNumber = 0;
for(int i = 0; i < dayHoursList.length; i++) {
if(dayHoursList[i].equals("?")) {
permutationNumber ++;
}
else {
weekHours -= Integer.parseInt(dayHoursList[i]);
}
}
/* In the case, find 2 numbers which are not larger then 8.*/
/* The sum of those 2 numbers should equal to 8 */
/* {0,8}{1,7}{2,6}{3,5}{4,4}{5,3},{6,2},{7,1},{8,0} */
List<List<Integer>> permuLists = new ArrayList<>();
int[] nums = new int[maxDayHours + 1];
for(int i = 0; i <= maxDayHours; i++) {
nums[i] = i;
}
backtracking(permuLists, new ArrayList<>(), nums, 0, permutationNumber, weekHours);
for(int i = 0; i < permuLists.size(); i++) {
List<Integer> list = permuLists.get(i);
int count = 0;
StringBuilder sb = new StringBuilder();
for(int j = 0; j < dayHoursList.length; j++) {
if(dayHoursList[j].equals("?")) {
sb.append(list.get(count++));
}
else {
sb.append(dayHoursList[j]);
}
}
results.add(sb.toString());
}
return results;
}
public static void backtracking(List<List<Integer>> list, List<Integer> tempList, int[] nums, int sum,
int permutationNumber, int target) {
if(tempList.size() == permutationNumber) {
if(sum == target) {
list.add(new ArrayList<>(tempList));
}
return;
}
for(int i = 0; i < nums.length; i++) {
tempList.add(nums[i]);
sum += nums[i];
backtracking(list, tempList, nums, sum, permutationNumber, target);
sum -= tempList.get(tempList.size() - 1);
tempList.remove(tempList.size() - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment